Skip to content Skip to sidebar Skip to footer

Listadapter To Modify The Datasource (which Is An Arraylist)

here's a problem that i've run into lately: I have a listview with a custom adapter class, the adapter takes in a listview and populates the listview with elements from it. Now, i'

Solution 1:

I've done something like that:

publicclassMyAdapterextendsAdapter {

privatefinal ArrayList<String> items = newArrayList<String>();

// ...

deleteRow(int position) {
    items.remove(position);
    notifyDataSetChanged();
}
//@Overridepublic View getView(int position, View convertView, ViewGroup parent) {

    if(convertView == null) {
        Tagtag=newTag();
        // inflate as usual, store references to widgets in the tag
        tag.button.setOnClickListener(newOnClickListener() {
        @OverridepublicvoidonClick(View v) {
                    deleteRow(position);
        }
    });
    }
    // don't forget to set the actual position for each rowTagtag= (Tag)convertView.getTag();
    // ...
    tag.position = position;
    // ...
}



classTag {

    int position;

    TextView text1;
    // ...
    Button button;
}

}

Solution 2:

In the getView() method, can't you just setOnClickListener() on the button?

Something like this:

staticfinalclassMyAdapterextendsBaseAdapter {

    /** override other methods here */@Overridepublic View getView(finalint 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 = newViewHolder();
            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(newOnClickListener() {
            @OverridepublicvoidonClick(View v) {
                // do something depending on position
                performSomeAction(position);
                // mark data as changed
                MyAdapter.this.notifyDatasetChanged();
            }
        }
    }
    staticfinalclassViewHolder {
        // references to widgets
        Button mButton;
    }
}

If you're unsure about extending BaseAdapter, check out example List14 in ApiDemos. This techniques provides you with a flexible way to modify just about any aspect of your adapter, though it's quite some work.

Post a Comment for "Listadapter To Modify The Datasource (which Is An Arraylist)"