To change a button state without anything else is done via
btn1.getBackground().setState(new int[]{android.R.attr.state_pressed});
To reset to ordinary, you use
btn1.getBackground().setState(new int[]{android.R.attr.state_enabled});
A Button
's states can be found out via
btn1.getBackground().getState();
which resturns an int[]
. You can compare its values to android.R.attr
to find out which states are set.
private void simulateClick(final ImageButton button,
final long clickDuration) {
button.getBackground().setState(new int[]{android.R.attr.state_pressed});
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(clickDuration);
} catch ( InterruptedException e ) {
// not bad if interrupted: sleeps a bit faster (can happen?)
}
Count.this.runOnUiThread(new Runnable() {
public void run() {
button.getBackground().setState(new int[]{android.R.attr.state_enabled});
}
});
}}).start();
}
Explanation
Each View
has a Drawable
as background image. A Drawable
can be of different subtypes, here it is a StateListDrawable, as defined per XML. (See @Lynx's answer as an example of a XML defined drawable).
This Drawable
can be told which state it is to assume (via setState
) and does the layout itself.