Question

I want to change the color back to default color.

If suppose I click on the Button; the color of button must change. And if I click on the same Button again... the color must set back to default.

How can I achieve this...

b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (clicked) {
                    holder.b1.setBackgroundResource(R.drawable.like_icon_hover);
                } else {
                    holder.b1.setBackgroundResource(R.drawable.like_icon);
                }
                clicked = false;
            }
        });
Was it helpful?

Solution

Try this way

b1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (clicked) {
                holder.b1.setBackgroundResource(R.drawable.like_icon_hover);
                clicked = false;
            } else {
                holder.b1.setBackgroundResource(R.drawable.like_icon);
                clicked = true;
            }

        }
    });

Or Create a Selector in drawable/selector.xml like:

<?xml version="1.0" encoding="utf-8"?>
  <selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item
   android:state_pressed="true"
   android:drawable="@drawable/like_icon_hover" />
  <item
   android:state_pressed="false"
   android:drawable="@drawable/like_icon" />
 </selector>

And set this Selector as a Background to your Button like:

android:background="@drawable/selector"

OTHER TIPS

b1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (clicked) {
                holder.b1.setBackgroundResource(R.drawable.like_icon_hover);
            } else {
                holder.b1.setBackgroundResource(R.drawable.like_icon);
            }
            clicked = !clicked;
        }
    });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top