recycled recyerview item keeps the old background color

此生再无相见时 提交于 2019-12-11 12:45:49

问题


I have a recycler view and inside the onClick(View view) i'm changing the background color to almost transparent red view.setBackgroundColor(Color.argb(64, 183, 28, 28)); but something weird is happening which is when I scroll down I see the color has changed for items that have not been clicked yet, my guess is when the item is recycled it is retaining the color. I want to remove that color but removing it inside the constructor for the holder is not working so my question is how do I go about that?

EDIT: after the comment this is more detailed code

public class GridHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    public TextView Name;
    public ImageView Photo;
    public GridHolder(View itemView) {
        super(itemView);
        itemView.setOnClickListener(this);
               Name = (TextView) itemView.findViewById(R.id.name);
        Photo = (ImageView) itemView.findViewById(R.id.photo);
        itemView.setClickable(true);
    }

    @Override
    public void onClick(View view) {

            view.setBackgroundColor(Color.argb(64, 183, 28, 28));
        }
    }

回答1:


The simplest way to achieve this in my opinion is to give each item in your RecyclerView a state (boolean) and set the background depending on the state. This way when you recycle the view, the correct background is drawn.

if(isClicked){
    itemView.setBackgroundColor(Color.RED);
}
else{
    itemView.setBackgroudnColor(Color.WHITE);
}



回答2:


You should set all attributes in your onBindViewHolder(), because, as you can see, view may not be fresh but recycled and show state of previously presented record. So if background color maters, you must set it too in onBindViewHolder().




回答3:


You need to maintain the state of the background colour outside the ViewHolder (maybe in the Adapter or higher up). Then, in the onBindViewHolder of your Adapter, you set the background colour of your ViewHolder based on that state.



来源:https://stackoverflow.com/questions/37122098/recycled-recyerview-item-keeps-the-old-background-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!