您好我想在Recycler视图中更改特定项目的颜色。 我已经使用此代码完成了这项工作。
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
LayoutInflater inflater;
Context context;
clickME click;
View view;
ArrayList<String > data;
public CustomAdapter(Context context,ArrayList<String> data) {
this.context=context;
this.data=data;
inflater= LayoutInflater.from(context);
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
view=inflater.inflate(R.layout.list_row,parent,false);
MyViewHolder holder=new MyViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
int select=4;
if(select == position) {
view.setBackgroundColor(Color.BLUE);
Toast.makeText(context,""+position,Toast.LENGTH_SHORT).show();
} else {
view.setBackgroundColor(Color.parseColor("#214F4B"));
Toast.makeText(context,""+position,Toast.LENGTH_SHORT).show();
}
holder.tv_title.setText(data.get(position));
}
我已成功更改位置4中项目的背景颜色,但是当我向下滚动时,位置14处项目的背景颜色也会发生变化。我不知道为什么会发生这种情况才能解决我的问题
答案 0 :(得分:4)
问题是您没有回收view
视图。您尚未发布ViewHolder代码,但应在holder.view.setBackgroundColor(...)
方法中使用view.setBackgroundColor(...)
代替onBindViewHolder
。
答案 1 :(得分:1)
您不应该重复使用onCreateViewHolder()
的观看次数。代码将是这样的:
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.list_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
int select = 4;
if (select == position) {
holder.itemView.setBackgroundColor(Color.BLUE);
Toast.makeText(context, "" + position, Toast.LENGTH_SHORT).show();
} else {
holder.itemView.setBackgroundColor(Color.parseColor("#214F4B"));
Toast.makeText(context, "" + position, Toast.LENGTH_SHORT).show();
}
holder.tv_title.setText(data.get(position));
}