简体   繁体   中英

Android (java) - Adapter onClickListener method always return last item

I need to get the ID of the current item in my adapter but it only returns the id of the last added item. I can't figure out how to get around this.

            @Override
            protected void onBindViewHolder(ViewHolder holder, final int position, CardViewModel cardViewModel) {

   button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Log.d("id: ",cardViewModel.getId());
                    }
                });

            }

Click on the 1st, 2nd and 3rd item in order and output:

3 3 3

Must be:

1 2 3

My button isn't for my adapter view so I can't use: holder.button

Thanks...

EDIT:

卡片视图

When I click the button, I need to get the name on the cardView, but each time it returns the name on the last card.

Instead of getting cardViewModel.getId() use position variable it will return current position of item click. You need to use ArrayList or List of CardViewModel cardViewModel as parameter then you will be able to get id of clicked item by

You need to pass List of CarViewModel as follows:

protected void onBindViewHolder(ViewHolder holder, final int position, ArrayList <CardViewModel> cardViewModelList)

You can retrieve the id of the current item clicked as follows:

CardViewModel cardviewModel = cardViewModelList.get(position)

This will give you expected result:

Log.d("id: ",cardViewModel.getId());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM