How Can I change the button background when is pressed and keep changing after I stop pressing it?

I have this code, when I press the button the background changes, but when I stop pressing the button, returns to the first background.

<item android:drawable="@drawable/botonverdeencendido" android:state_pressed="true"/>
<item android:drawable="@drawable/botonverdeapagado"/>

Upvotes: 0

Views: 95

Answers (3)

Jay Mungara
Jay Mungara

Reputation: 7150

To change the background color of button when pressed you can do it like,

btn.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            //Button pressed color
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                btn.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
            }

            // Button pressed stopped
            if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
                btn.setBackgroundColor(getResources().getColor(R.color.colorAccent));
            }
            return false;
        }
    });

I think this will work for you.

Upvotes: 1

Salman Qadami
Salman Qadami

Reputation: 174

you should add:

android:state_selected="true"

your drawable will be like this:

<item android:drawable="@drawable/botonverdeencendido" android:state_selected="true" />
<item android:drawable="@drawable/botonverdeencendido" android:state_pressed="true" />
<item android:drawable="@drawable/botonverdeapagado" />

Upvotes: 0

Goutham
Goutham

Reputation: 347

Implement onClick() function for the particular button

In the layout file,

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Click ME!"/>

In the activity,

Button button = findViewById(R.id.button);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            v.setBackgroundColor(Color.RED);
        }
    });

This will help u I guess.

Upvotes: 0

Related Questions