To make it a bit clearer if you are just in need of a two state button:
You do not need your own button.xml
. You can work with the normal of Android.
The button.setPressed(true)
will not work if you are clicking the button, because Android will reset it once you let go of the button. Try to set another buttons setPressed
state first to see the effect.
Which means, to use it on the same button it must be set delayed. Here is a working example. Of course, the mentioned approach (by long id 18..) on changing the background works too.
private final Handler mHandler = new Handler();
rootView.findViewById(R.id.yourButton).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
boolean pressed = false;
if (v.getTag() instanceof Boolean)
pressed = (boolean) v.getTag();
final boolean newPressed = !pressed;
// setTag to store state
v.setTag(newPressed);
final View vRun = v;
Runnable run = new Runnable() {
@Override
public void run() {
vRun.setPressed(newPressed);
}
};
mHandler.post(run);
// mHandler.postDelayed(run, 5);
}
});