setOnClickListener更改recyclerview中的每七个视图 [英] setOnClickListener changes every seventh view in recyclerview
问题描述
当我在Recyclerview中单击一个项目时,每七个项目都会产生效果.
when i click an item in Recyclerview every seventh item gets the effect.
onBindViewHolder:
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
推荐答案
不要在onBindViewHolder中使用onClickListener,而是在onCreateViewHolder中设置它,并创建一个成员变量来设置所选项目.您可以这样做.
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;
//在您的createViewHolder方法中
// 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"));
}
这篇关于setOnClickListener更改recyclerview中的每七个视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!