android - Change button background color as if pressed, but without the user pressing it -


on android, button changes background color when pressed.

how can tell button pressed (without firing onclick-action), changes color, without user pressing it? (for example triggered swipe action)

it should change color briefly, , change back.

there quite a few questions concerning keeping pressed state. question asks, how set button_pressed state briefly, if clicked, without real click.

button.setpressed(true) has not given color change, neither has button.performclick().

to change button state without else done via

btn1.getbackground().setstate(new int[]{android.r.attr.state_pressed}); 

to reset ordinary, use

btn1.getbackground().setstate(new int[]{android.r.attr.state_enabled}); 

a button's states can found out via

btn1.getbackground().getstate(); 

which resturns int[]. can compare values android.r.attr find out states set.

explanation

each view has drawable background image. drawable can of different subtypes, here statelistdrawable, defined per xml. (see @lynx's answer example of xml defined drawable).

this drawable can told state assume (via setstate) , layout itself.


Comments