Selector for Buttons not working after setting backgroundResource of the button in Android
I have applied the follwoing selector to all my buttons by specifying it in my theme:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/my_btn_pressed"
android:state_pressed="true" />
<item android:drawable="@drawable/my_btn_focussed"
android:state_focused="true" />
<item android:drawable="@drawable/my_btn_normal" />
</selector>
This works fine. But I want the background of the button to remain "@drawable/my_btn_pressed" when the button is pressed, as if to highlight that this was the last button pressed. Hence, I added the code in my onClick()
to set the background resource:
infoButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
infoButton.setBackgroundResource(R.drawable.my_btn_pressed);
otherButton.setBackgroundResource(R.drawable.my_btn_normal);
}
});
This also works to highlight the last pressed button with "my_btn_pressed". However afte开发者_JAVA技巧r this, my selector properties do not seem to work on the other buttons. Mainly, the state focussed is not distinguishable, at all.
Any idea how I can do both, i.e distinguish focussed, pressed and normal states of the button, as well as highlight the last pressed button?
Hmm, the solution I found for this one may not be really correct, but I used this workaround, since I had no other go!
When the info button is focussed, i.e in onFoucsChangeListener()
, use infoButton.setSelected(true);
and similarly, set all other buttons as unselected. Do not set the background resource!
In selector.xml, add an item
<item android:drawable="@drawable/my_btn_focussed"
android:state_focused="true" />
This should help in setting the selected button as highlighted!
精彩评论