0

I want to change the background of Card View on Long Press and I have visited so many forum but no one gave the proper answer.

So, How to change the background of list/card/recycler view just like the long press on navigation view items ??

2 Answers2

4

I guess, you are trying to implement Ripple Effect on CardView. To achieve that, add the following attributes to your CardView in xml:

android:foreground="?android:attr/selectableItemBackground"
android:clickable="true"

Hope this helps. Source.

Community
  • 1
  • 1
tahsinRupam
  • 6,325
  • 1
  • 18
  • 34
0

If you use RecyleView. You have to use onLongClickListener() event on Adapter of RecyleView. Just like -

    @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
                final ViewHolder holder = (ViewHolder) holder;

                //go news details fragment
                holder.newsContentLayout.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public void onLongClick(View v) {
                    // change you cardview background
                     holder.cvCardView.setImageDrawable(holder.cvCardView.getContext().getResources()
                          .getDrawable(R.drawable.bg_cardview));

                    }
                });
        }

If you use ListView then you can do it by -

listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

          CardView cardView = (CardView)  view.findViewById(R.id.cardview);
            cardView.setBackgroundDrawable(getApplicationContext().getResources().getD    rawable(R.drawable.background));
                    return false;
                }
            });
AGM Tazim
  • 2,213
  • 3
  • 16
  • 25