I can’t implement a Recycler View listener that will respond to its individual elements. Let's say I have a Recycler View of four elements, I want to open different fragments by clicking.
I tried to use this code:
public static class ItemHolder extends RecyclerView.ViewHolder implements View.OnClickListener { TextView mText; Button mButton; CardView mCard; public ItemHolder(View v) { super(v); mCard = (CardView) v.findViewById(R.id.item_card); mText = (TextView) v.findViewById(R.id.item_text); mButton = (Button) v.findViewById(R.id.item_button); mCard.setOnClickListener(this); mButton.setOnClickListener(this); } @Override public void onClick(View v) { int position = getAdapterPosition(); if (position != RecyclerView.NO_POSITION) { switch (v.getId()) { case R.id.card: itemClick(position); break; case R.id.button: buttonClick(position); } } } private void itemClick(int position){ //action on item click } private void buttonClick (int position){ //action on button click } }
In addition, I can’t figure out what id to use:
@Override public void onClick(View v) { int position = getAdapterPosition(); if (position != RecyclerView.NO_POSITION) { switch (v.getId()) { case R.id.card: itemClick(position); break; case R.id.button: buttonClick(position); } } }