简体   繁体   中英

Android RecyclerView.Adapter change icon onClick

I created a list item with a icon at the end. Using RecyclerView.Adapter

On icon onClick, I want to change the icon. (I can do it). But when you scroll the list up or down there will be others random list item icon changed.

public void onBindViewHolder(StatusViewHolder holder, int position) {
                ...

final InviteFriend data = mInviteFriend.get(position);

    if(data.isSelected()) { 

                holder.imageView.setImageResource(R.drawable.ic_person_black_24dp); }
                holder.imageView.setTag(data);

                holder.imageView.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View view) {
                        ImageView imageView = (ImageView) view;
                        InviteFriend inviteFriend = (InviteFriend) imageView.getTag();
                        inviteFriend.setSelected(true);
                        imageView.setImageResource(R.drawable.ic_person_black_24dp);
                        notifyCounterChanged(true);
                    }
                });

    }

In recycler view the view will be recycled to save memory usage
so you need to add else in your condition

if(data.isSelected()) { 
    // your original code
} else {
    holder.imageView.setImageResource(R.drawable.your_drawable);
    //Put another code if you want
}

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