0

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

2 Answers 2

2

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"
Sign up to request clarification or add additional context in comments.

2 Comments

simple and nice answer,,,
I'm trying to do the same but asks me to end or holder can not be accessed from the event click
0
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;
        }
    });

1 Comment

I'm trying to do the same but asks me to end or holder can not be accessed from the event click

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.