SocialSupaCrew
SocialSupaCrew

Reputation: 464

Multiple onClickListener in a RecyclerView

I have a RecyclerView with multiple items. Each Item have multiple button to do some actions. So I have implemented the View.OnClickListener to my RecyclerViewAdapter.

But it's seems like I can only set one OnClickListener in the onCreateViewHolder function.

Does anyone know any solution to have multiple button in each items of my RecyclerView ?

Upvotes: 1

Views: 2823

Answers (1)

Felipe Kenji Shiba
Felipe Kenji Shiba

Reputation: 714

You could implement OnClickListener and inside onClick function implement each action. Like this.

static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    Button button1;
    Button button2;
    Button button3;
    Button button4;

    public MyViewHolder(View itemView) {
        super(itemView);
        button1 = (Button) itemView.findViewById(R.id.button1);
        button2 = (Button) itemView.findViewById(R.id.button2);
        button3 = (Button) itemView.findViewById(R.id.button3);
        button4 = (Button) itemView.findViewById(R.id.button4);

        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
        button3.setOnClickListener(this);
        button4.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (view == button1) {
            // button1 action
        } else if (view == button2) {
            // button2 action
        } else if (view == button3) {
            // button3 action
        } else if (view == button4) {
            // button4 action
        }
    }
}

Upvotes: 4

Related Questions