I am implementing multiple ViewHolders as suggested in this answer which uses an abstract bind()
. My current Adapter
and ViewHolder
looks likes:
// MyAdapter.java
{adapter code}
public static abstract class MyViewHolder extends RecyclerView.ViewHolder {
public MyViewHolder(View itemView) {
super(itemView);
}
protected abstract void bind(MyModel item);
}
// ViewHolder1.java
public class ViewHolder1 extends MyAdapter.MyViewHolder implements View.OnClickListener {
TextView textView;
public ViewHolder1(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.textView);
textView.setOnClickListener(this);
}
@Override
protected void bind(MyModel item) {
textView.setText(item.getText());
}
@Override
public void onClick(View view) {
//pass the current item position back to adapter
}
}
How can I pass the position of the clicked item from here back to the adapter. I don't want set onClickListener()
inside bind()
because it would then be called multiple times while my RecyclerView
is scrolled.
View
type, but it's the same thing, as far as the position. – ConcomitanceViewHolder
class beingabstract
isn't really relevant. Apart from that, which external class are you talking about? ThegetAdapterPosition()
method is a member ofRecyclerView.ViewHolder
, so you can call it in anyViewHolder
descendant. – ConcomitanceMyViewHolder(View itemView, ActionListener listener)
in the constructor instead of just itemView would do the work? I just wanted to make sure I am achieving this without leaks. Also, always thoughtgetAdapterPosition()
method was accessible to Adapter class only. My bad. – StercoricolousViewHolder
s, and theActivity
will outlive them, anyway. – Concomitance