简体   繁体   English

在recylerview android中更改特定项目的颜色

[英]change the color of specific item in recylerview android

hello i want to change the color of specific items in recycler view. 你好,我想在回收站视图中更改特定项目的颜色。 i have done this using this code. 我已经用这段代码做到了。

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));



}

but the output is 但输出是 在此处输入图片说明

在此处输入图片说明

i have successfully change the background color of item in position 4, but when i scroll down the background color of item at position 14 also change. 我已经成功更改了位置4的项目的背景色,但是当我向下滚动时位置14的项目的背景色也发生了变化。 i don't know why this happening kindly solve my issue 我不知道为什么这种情况会很好地解决我的问题

The problem is you're not recycling your view View. 问题是您没有回收view View。 You have not posted your ViewHolder code, but you should use holder.view.setBackgroundColor(...) instead of view.setBackgroundColor(...) in your onBindViewHolder method. 您尚未发布ViewHolder代码,但应在onBindViewHolder方法中使用holder.view.setBackgroundColor(...)而不是view.setBackgroundColor(...)

You shouldn't reuse view from onCreateViewHolder() . 您不应该重复使用onCreateViewHolder()视图。 Code will be something like this: 代码将如下所示:

@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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM