Android. How do I keep a button displayed as PRESSED until the action created by that button is finished?

user527405 picture user527405 · Jan 12, 2011 · Viewed 12k times · Source

I have button_focused, button_pressed, and button_normal images. When I press the button, the button_pressed image is displayed and the action related to the button pressing begins.

When I quit pressing the button, the action continues but the button returns to button_normal image being displayed.

How can I set the button image being displayed to button_pressed during the entire action then reset to the button_normal image?

Thank you for your time

Answer

18446744073709551615 picture 18446744073709551615 · Oct 7, 2013

I used a function like

void setHighlighted(boolean highlight) {
    button.setBackgroundResource( highlight
                                ? R.drawable.bbg_pressed
                                : R.drawable.button_background);
}

where button_background is a selector defined in button_backgroung.xml:

<?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/bbg_pressed"></item>
    <item android:state_focused="true" android:drawable="@drawable/bbg_selected"></item>
    <item android:drawable="@drawable/bbg_normal"></item>
</selector>

That is, this code does not interfere with the pressed state used by the Android framework; instead, it changes the background so that the button looks pressed.