-2

I've seen all the questions which have similar problems, but in all solutions Drawables are used. I don't want to use an Image or a Drawable.

I have a custom round Button. By default its color is set to #00796B. Now when the Button is clicked it should change the color to #00695C for example and as soon as it gets released it should change back to the default color.

What do I have to do in onClickListener event of Button to achieve what I want?

Below is my code.

btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Vibrator mvibrate = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
            mvibrate.vibrate(500);
        }

    });

I want to know that if there is any way we can use if condition to check the state of button and according to it do action?

EDIT :- I have successfully achieve what i wanted. Thanks guys for your answer and support.

1 Answers1

0

First make a xml in drawable folder save it with name button_selector.xml

    <?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="#004F81" />
            <stroke
                android:width="1dp"
                android:color="#222222" />
            <corners
                android:radius="7dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:startColor="#89cbee"
                android:endColor="#004F81"
                android:angle="270" />
            <stroke
                android:width="1dp"
                android:color="#4aa5d4" />
            <corners
                android:radius="7dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>

Then in layout xml where you have defined your button set background of that button as :

<Button
.
.
android:Background="@drawable/button_selector"/>
Pankaj
  • 7,908
  • 6
  • 42
  • 65