ListAdapter to change data source (which is an arraylist)
here is the problem i ran into lately: I have a listview with a custom adapter class, the adapter takes a listview and populates the listview with items from it. Now, I would like to have a button on each row of the list to remove an item from it. How should I approach this problem? Is there a way to remotely trigger a method on the activity class and call the notifydatachanged () method on the adapter to update the list?
a source to share
I did something like this:
public class MyAdapter extends Adapter {
private final ArrayList<String> items = new ArrayList<String>();
// ...
deleteRow(int position) {
items.remove(position);
notifyDataSetChanged();
}
//
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
Tag tag = new Tag();
// inflate as usual, store references to widgets in the tag
tag.button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
deleteRow(position);
}
});
}
// don't forget to set the actual position for each row
Tag tag = (Tag)convertView.getTag();
// ...
tag.position = position;
// ...
}
class Tag {
int position;
TextView text1;
// ...
Button button;
}
}
a source to share
In the getView () method, can't you just set the OnClickListener () on the button?
Something like that:
static final class MyAdapter extends BaseAdapter {
/** override other methods here */
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
// inflate the view for row from xml file
// keep a reference to each widget on the row.
// here I only care about the button
holder = new ViewHolder();
holder.mButton = (Button)convertView.findViewById(R.id.button);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
// redefine the action for the button corresponding to the row
holder.mButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// do something depending on position
performSomeAction(position);
// mark data as changed
MyAdapter.this.notifyDatasetChanged();
}
}
}
static final class ViewHolder {
// references to widgets
Button mButton;
}
}
If you are unsure about distributing BaseAdapter, see the List14 example in ApiDemos. These methods provide you with a flexible way to change almost any aspect of your adapter, although it works pretty well.
a source to share