Some XML attributes of buttons (such as background, textColor, etc) can be defined with color or drawable state List like this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:color="#ffff0000"/>
<item android:state_focused="true"
android:color="#ff0000ff"/>
<item android:state_enabled="true"
android:color="#ff00ffff"/>
<item android:color="#ff000000"/>
</selector>
When view state changes (pressed/unpressed, for example), corresponding color is changed automatically.
How can I prograqmmatically handle some kind of stateChangedEvent to perform more complicated layout change, than just changing a color (for example, change font size or set another text)?
For focus changes and touch events you can register listeners by setOnFocusChangeListener and setOnTouchListener. And changes about disabled/enabled states you can perform directly after changing your button state.
// use the selector method to pass your button and image // you can use color also
b1=(Button)findViewById(R.id.button1);
// b2=(Button)findViewById(R.id.button2);
selector(b1, R.drawable.image_1_2, R.drawable.image_1);
// selector(b2, R.drawable.image_2_2, R.drawable.image_2);
}
public void selector(Button b,int pressed_image,int normal_image )
{
StateListDrawable states = new StateListDrawable();
states.addState(new int[] {android.R.attr.state_pressed},
getResources().getDrawable(pressed_image));
states.addState(new int[] { },
getResources().getDrawable(normal_image));
b.setBackgroundDrawable(states);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With