Issue
On Android, a Button
changes its background color when pressed.
How can we tell a button that it is pressed (without firing the onClick
-action), so that it changes color, without the user pressing it? (for example triggered by a swipe action)
It should change color briefly, and then change back.
There a quite a few questions concerning keeping the pressed state. This question asks, how to set the button_pressed
state briefly, as if clicked, but without a real click.
Button.setPressed(true)
has not given a color change, neither has Button.performClick()
.
Solution
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.
Example Code
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.
Answered By - serv-inc
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.