user6265154
user6265154

Reputation: 363

click listener in OnBindViewholder recyclerview android

In the below code 'setlisteners' method is called every time,should'nt value of position change? There is only one method'setlisteners'in which parameter position is passed,but when in log ,i see that whenever click event happens on my buttons,it shows correct position. should'nt position overwrite itself and show incorrect position because click event can happen at any time ,by that time value of position will have changed?

let's suppose 5 views have been binded and i click on the first itemview,then should'nt it show me the last position held by the last binded itemview?

 @Override
 public void onBindViewHolder(ViewHolder holder, int position) {


     setListeners(holder,position);


    }

private void setListeners(ViewHolder holder, final int position) {
        holder.updownarrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("ddfg",""+position);

            }
        });
        holder.leftlayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }

position will hold the position of the last holder which was bind in onBindViewHolder, since my View does not call onBindViewHolder when i click on it,should'nt position hold the position last binded and show only that one position whenever any view gets clicked?

Upvotes: 2

Views: 971

Answers (3)

Sammy T
Sammy T

Reputation: 1924

The position in onBindViewHolder is the same as the position in your adapter/data set. Your Click Listener is being set with the position the individual ViewHolder represented in your data set at the time of binding. Even though the click event isn't being called until after all your Views are binded, each function instance was already set up to use the corresponding position each view was set with.

If each View shared the same instance of a Click Listener, then you would only get the last position. But, each View holds its own instance of a Click Listener.

Upvotes: 1

Tin Tran
Tin Tran

Reputation: 2285

Dont use the position in onBindViewHolder. use this:

final int adapterPosition = viewholder.getAdapterPosition();
// do what ever with it

Upvotes: 0

yennsarah
yennsarah

Reputation: 5517

No, position will hold the position of the last holder which was bin in onBindViewHolder, since your View does not call onBindViewHolder when you click on it.

There are many possibilities to retrieve the correct position - for example if you set & get the position in the Views tag or search for the surrounding ViewHolder and check its position in the adapter or layout.

Upvotes: 0

Related Questions