Android OnClickListener for RecyclerView's Child's Child

前端 未结 1 1442
一向
一向 2020-12-10 21:29

What I want to do is set an onClickListener for an ImageView that is in an item in a recyclerview. I only want a click on that ImageView to do CODE A and click anywhere else

相关标签:
1条回答
  • 2020-12-10 21:52

    Okay so this might not be the correct way to do it, but this is how I got it to work.

    Firstly create a click interface in your ViewHolder:

    private TaskListRecyclerviewClickInterface clickListener;
    

    ...

    this.clickListener = clickListener;
    

    ...

    public interface TaskListRecyclerviewClickInterface {
        public void onItemClicked(int position, String tag);
    }
    

    Then add an onclicklistener to the views you want and call this interface when these items are clicked like so:

    holder_view.setTag("holder");
    holder_view.setOnClickListener(this);
    imageView.setTag("ImageView");
    imageView.setOnclickListener(this);
    

    And the onClickListener :

    @Override
    public void onClick(View v) {
        if (clickListener != null) {
            clickListener.onItemClicked(getPosition(), v.getTag().toString());
        }
    }
    

    Now from your activity, pass this Interface to your Adapter in the constructor and then pass the interface to this viewholder like so:

    public InboxTaskListAdapter(List<Items> items, InboxTasksViewHolder.TaskListRecyclerviewClickInterface clickListener) {
            this.items = items;
            this.clickListener = clickListener;
        }
    

    In onCreateViewHolder you should pass the interface to the viewholder.

    Now in your Activity or fragment just implement this listener and override the onItemClicked method. You will now get the view position and tag that was clicked on.

    0 讨论(0)
提交回复
热议问题