justanoob
justanoob

Reputation: 1807

Single OnClickListener for multiple ViewHolders

My ViewHolder (inner) class:

static class HostViewHolder extends RecyclerView.ViewHolder {

    ImageButton button1;
    ImageButton button2;

    HostViewHolder(View listItemView) {
        super(listItemView);

        button1 = (ImageButton) listItemView.findViewById(R.id.button1);
        button2 = (ImageButton) listItemView.findViewById(R.id.button2);
    }
}

In onBindViewHolder() i attach OnClickListeners to the Buttons the following way:

@Override
public void onBindViewHolder(final HostViewHolder holder, int position) {
    holder.button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int pos = holder.getAdapterPosition();
            // doing something using the value of pos
        }
    });
    holder.button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int pos = holder.getAdapterPosition();
            // doing some other thing using the value of pos
        }
    });
}

It's working fine, but my problem with this approach is i'm creating a new OnClickListener instance for every ViewHolder, which feels kinda redundant.

I would like to create a single OnClickListener instance to use, but i cannot access the position and holder params of onBindViewHolder() that way.

Is this possible to achieve? If so, how?

Thanks in advance.

Upvotes: 2

Views: 172

Answers (2)

deejay
deejay

Reputation: 572

Yes its possible and you can achieve it, as @Gurupad suggested, using switch statement in onClick(View v) method. And from personal experience its the best way to handle more than one onClicks, it makes your code easy to read and understand for you and your team (if working with a team).

For further assistance using switch statement with buttons click

 public void onClick(View v) {
    switch (v.getId()){
     case R.id.button1:
     //some code here
     break;
     case R.id.button2:
     //some code here
     break;
  }
}

Upvotes: 0

Gurupad Mamadapur
Gurupad Mamadapur

Reputation: 989

You can attach onClickListener in the ViewHolder class itself.

static class HostViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    ImageButton button1;
    ImageButton button2;

    HostViewHolder(View listItemView) {
        super(listItemView);

        button1 = (ImageButton) listItemView.findViewById(R.id.button1);
        button2 = (ImageButton) listItemView.findViewById(R.id.button2);
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int position = getAdapterPosition();
        switch (v.getId()){
            //handle clicks
        }
    }
}

Upvotes: 2

Related Questions