简体   繁体   中英

how to handle list item widget from outside Adapter

I had a requirement where I need to implement a ListAdapter which should be used for only display purpose.
Each list item row contains a button.
I have written an Adapter subclass which extends BaseAdapater separately as a file not with in activity.
My query is I need to catch the Button click on listitem of list from activity.
In otherwords I need to handle widget click on a list item from outside Adapter class.

My code will be like below:

MyAdapter.java

public MyAdapter extends BaseAdapter
{
}

MyActivity.java

public class MyActivity extends Activity {
ListView lv = (findViewById) R.id.list;
lv.setAdapter(new MyAdpater());

//Here I need to capture widget click on list item
Can anyone help me in sorting out this issue ?
Thanks in Advance.

You can simply pass a custom interface t from the activity to the adapter, and to invoke it when each button is being clicked in getView method. Something like this:

   public MyAdapter extends BaseAdapter 
    { 
        private OnListItemClick onClickListener;

        public void setOnItemClickListener(OnListItemClick onClickListener)
        {
          this.onClickListener = onClickListener;
        }

        View getView(.....)
        {
            button  = view.findViewById(R.id.button);
            button.setOnClickListener(new OnClickListener()
              {
                 onClick(View view)
                 {
                    onClickListener.onListItemClick(position);
                 }

              }
             )

        } 

        public interface OnListItemClick{
          public void onListItemClick(int position);
         }

}

Extend BaseAdapter with your custom and add abstract method for invoke when button was clicked, here how it's gonna look like:

public abstract CustomAdapter extends BaseAdapter { 

   //custom constructors and other staff

    public View getView(int position, ...) {

        //custom view initialization

        Button button = view.findViewById(R.id.button);
        button.setOnClickListener(new OnClickListener() {

             @Override
             public void onClick(View view) {
                buttonClickEvent(position);
             }
        });
    }

    public abstract void buttonClickEvent(int position);
}

Later in your code before setting adapter, create instance of CustomAdapter where you could implement everything you want. Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM