2

I have a RecylerView adapter where I am handling onClicks in the onCreateViewHolder method, however I cannot figure out a way to get the current position. My current method looks like this:

 @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.card_small, parent, false); return new ViewHolder(itemView, new ViewHolder.IViewHolderClicks() { @Override public void onImage(ImageView image) { // Need the position for logic in here // for example, myArrayList.get(position); } }); } 

Does anybody know how to access the current position from within onCreateViewHolder?

1
  • If I stored the position in a class member variable and assigned it in the onBindViewHolder method would that be a reliable method? Commented Jun 27, 2015 at 20:20

2 Answers 2

2

In your onClick handler, call viewHolder.getAdapterPosition().

@Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.card_small, parent, false); final ViewHolder vh = ViewHolder(itemView, new ViewHolder.IViewHolderClicks() { @Override public void onImage(ImageView image) { int position = vh.getAdapterPosition(); } }); return vh; } 
Sign up to request clarification or add additional context in comments.

4 Comments

I've tried that before but I always get the error that the ViewHolder may not have been initialised yet.
can you make IViewHolderClicks() a setter instead of a constructor parameter ?
Sorry I forgot to update! But I made it a setter and it worked fine!
I am getting position -1, Please help me
2

onCreateViewHolder() is not the proper place to store the position. When the ViewHolder gets recycled, you will not get another call to onCreateViewHolder(), so you will not have a chance to "fix" the position when the ViewHolder is recycled.

You can instead do this in onBindViewHolder(), which gives you the position as one of its arguments and is called each time the ViewHolder is recycled.

2 Comments

That's what I was leaning towards, I will try this and see if it works! Cheers!
Don't add listener in onBindViewHolder because that position may change without rebinding the view.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.