Search code examples
androidandroid-listviewonclicklistenerlistview-adapter

Android: can I handle onClick of BaseAdapter items in Activity where the ListView is created?


I have a custom adapter for ListView using custom adapter which extends BaseAdapter. In this custom adapter I have a view holder that holds the items shown in every list item.

Can I get a click callback of certain list item child View IN the Activity where I create and fill my ListView?


Solution

  • In your adapter class:

    private ViewClickListener mViewClickListener;
    
    public interface ViewClickListener {
        void onImageClicked(int position);
    }
    
    public void setViewClickListener (ViewClickListener viewClickListener) {
        mViewClickListener = viewClickListener;
    }
    

    You let your Activity implement ViewClickListener interface. Remember to call myAdapter.setViewClickListener(this); in the Activity

    In the getView method:

    imageView.setOnClickListener(new OnClickListener() {
    
        @Override
        public void onClick(View v) {
            mViewClickListener.onImageClicked(position);
        }
    });