setOnClickListener changes every seventh view in recyclerview

人走茶凉 提交于 2019-12-12 04:38:20

问题


when i click an item in Recyclerview every seventh item gets the effect.

onBindViewHolder:

public void onBindViewHolder(final ViewHolder holder, final int position) {
        holder.channelName.setText(list.get(position).getChannnelName());
        holder.linearLayoutChannelName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                view.setBackgroundColor(Color.parseColor("#93bcff"));
            }
        });
    }
    public class ViewHolder extends RecyclerView.ViewHolder {
        LinearLayout linearLayoutChannelName;
        TextView channelName;
        public ViewHolder(View itemView) {
            super(itemView);
            channelName = itemView.findViewById(R.id.tv_channel_name);
            linearLayoutChannelName = itemView.findViewById(R.id.ll_channelname);
        }
    }

when i click an item every seventh item changes its backgroung color,and it repeats every seventh item in the list, and even when scrolling across the list the background color dissapears.

https://i.stack.imgur.com/oq2sb.jpg

https://i.stack.imgur.com/rOzQg.jpg


回答1:


Don't use onClickListener in onBindViewHolder instead set it in onCreateViewHolder and create a member variable to set the selected item. You can do it like this.

int mSelectedItemPosition = -1;

// in your createViewHolder method

holder.linearLayoutChannelName.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                int position = holder.getAdapterPosition();
                if (position != RecyclerView.NO_POSITION) {
                  mSelectedItemPosition = position;
                  notifyItemRangeChanged(0, yourList.size());
                }
            }
        });

And in your bind view holder check selected item position and set the background color

if(mSelectedItemPosition == position){
  view.setBackgroundColor(Color.parseColor("#yourColor"))
}else{
  view.setBackgroundColor(Color.parseColor("originalColor"));
}


来源:https://stackoverflow.com/questions/46114794/setonclicklistener-changes-every-seventh-view-in-recyclerview

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