nabir
nabir

Reputation: 1497

How to get position from onCreateViewHolder

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?

Upvotes: 2

Views: 5696

Answers (2)

yigit
yigit

Reputation: 38243

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;
}

Upvotes: 2

Karakuri
Karakuri

Reputation: 38585

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.

Upvotes: 2

Related Questions