Changing background color of selected item in recy

2020-01-24 11:28发布

How to change the background color of only selected view in my recycle view example?only the background color of clicked itemview needs to be changed. Only one selected item must be displayed with background color change at a time and the rest needs to be as before selecting. here is my code :

MainActivity

public class MainActivity extends AppCompatActivity {
RecyclerView rv1;
    private  final String android_versions[]={
                "Donut",
                "Eclair",
                "Froyo",
                "Gingerbread",
                "Honeycomb",
                "Ice Cream Sandwich",
                "Jelly Bean",
                "KitKat",
                "Lollipop",
                "Marshmallow"
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
    }

    private  void initViews(){
        rv1=(RecyclerView)findViewById(R.id.recyclerView1);
        rv1.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(getApplicationContext());
        rv1.setLayoutManager(layoutManager);

        RecyclerDataAdapter rda=new RecyclerDataAdapter(rv1,getApplicationContext(),android_versions);
        rv1.setAdapter(rda);
    }
}

RecyclerDataadapter

public class RecyclerDataAdapter extends RecyclerView.Adapter<RecyclerDataAdapter.ViewHolder> {

private String android_versionnames[];
    private Context context1;

    private RecyclerView mRecyclerView;


    public RecyclerDataAdapter(RecyclerView recylcerView,Context context,String android_versionnames[]){
        this.android_versionnames=android_versionnames;
        this.context1=context;
mRecyclerView=recylcerView;
        setHasStableIds(true);
        System.out.println("Inside dataadapter,Android names : \n ");
        for(int i=0;i<android_versionnames.length;i++){
            System.out.println("\n"+android_versionnames[i]);
        }
    }


    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        holder.tv1.setText(android_versionnames[position]);
    }


    @Override
    public int getItemCount() {
        return android_versionnames.length;
    }


    public class ViewHolder extends RecyclerView.ViewHolder {
        private TextView tv1;
        LinearLayout row_linearlayout;
        RecyclerView rv2;

        public ViewHolder(final View itemView) {
            super(itemView);
            tv1=(TextView)itemView.findViewById(R.id.txtView1);
            row_linearlayout=(LinearLayout)itemView.findViewById(R.id.row_linrLayout);
            rv2=(RecyclerView)itemView.findViewById(R.id.recyclerView1);
            /*itemView.setBackgroundColor(0x00000000);//to transparent*/

        }
    }
}

15条回答
唯我独甜
2楼-- · 2020-01-24 11:51

I was able to change the selected view color like this. I think this is the SIMPLE WAY (because you don't have to create instance of layouts and variables.

MAKE SURE YOU DONT GIVE ANY BACKGROUND COLOR INSIDE YOUR RECYCLER VIEW's TAG.

holder.itemView.setBackgroundColor(Color.parseColor("#8DFFFFFF"));

onBindViewHolder() method is given below

@Override
public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) {

        holder.item_1.setText(list_items.get(position).item_1);
        holder.item_2.setText(list_items.get(position).item_2);
        holder.select_cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isChecked){

                    holder.itemView.setBackgroundColor(Color.parseColor("#8DFFFFFF"));
                }else {

                    holder.itemView.setBackgroundColor(Color.parseColor("#FFFFFF"));
                }
            }
        });
}
查看更多
孤傲高冷的网名
3楼-- · 2020-01-24 11:55

Create a selector into Drawable folder:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
<item android:state_pressed="true">
   <shape>
         <solid android:color="@color/blue" />
   </shape>
</item>

<item android:state_pressed="false">
    <shape>
       <solid android:color="@android:color/transparent" />
    </shape>
</item>
</selector>

Add the property into your xml (where you declare the RecyclerView):

android:background="@drawable/selector"
查看更多
Summer. ? 凉城
4楼-- · 2020-01-24 11:56

I got it like this

public void onClick(View v){
        v.findViewById(R.id.textView).setBackgroundColor(R.drawable.selector_row);
 }

Thanks

查看更多
唯我独甜
5楼-- · 2020-01-24 11:57

I can suggest this solution, which I used in my app. I've placed this code of onTouchListener in my ViewHolder class's constructor. itemView is constructor's argument. Be sure to use return false on this method because this need for working OnClickListener

itemView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN)
        {
            v.setBackgroundColor(Color.parseColor("#f0f0f0"));
        }
        if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL)
        {
            v.setBackgroundColor(Color.TRANSPARENT);
        }
        return false;
    }
});
查看更多
三岁会撩人
6楼-- · 2020-01-24 11:58

Add click listener for item view in .onBindViewHolder() of your RecyclerView's adapter. get currently selected position and change color by .setBackground() for previously selected and current item

查看更多
相关推荐>>
7楼-- · 2020-01-24 12:06

My Solution

With my solution I'm not using notifyDataSetChanged(), because annoying whenever item is clicked, all the items from list got refreshed. To tackle this problem, I used notifyItemChanged(position); This will only change the selected item.

Below I have added the code of my omBindViewHolder.

private int previousPosition = -1;
private SingleViewItemBinding previousView;

@Override
public void onBindViewHolder(@NonNull final ItemViewHolder holder, final int position) {
    holder.viewBinding.setItem(itemList.get(position));
    holder.viewBinding.rlContainerMain.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            clickRecyclerView.clickRecyclerItem(position, 0);

            previousPosition = position;
            notifyItemChanged(position);

            if(previousView != null){
                previousView.rlContainerMain.setBackgroundColor(
                        ContextCompat.getColor(context, R.color.colorGrayLight));

            }
        }
    });

    if(position == previousPosition){
        previousView = holder.viewBinding;

        holder.viewBinding.rlContainerMain.setBackgroundColor(
                ContextCompat.getColor(context, R.color.colorPrimary));

    }
    else {
        holder.viewBinding.rlContainerMain.setBackgroundColor(
                ContextCompat.getColor(context, R.color.colorGrayLight));

    }

}
查看更多
登录 后发表回答