How to set state color of button in android?
I want to custom button ,
If user pressed it will show red color and still show red until user pressed other button
how to开发者_StackOverflow do this? thanks.
Try this code:
final Button b1 = (Button)findViewById(R.id.btn_1);
final Button b2 = (Button)findViewById(R.id.btn_2);
b1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
b1.setBackgroundColor(Color.RED);
b2.setBackgroundColor(Color.WHITE);
}
});
b2.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
b2.setBackgroundColor(Color.RED);
b1.setBackgroundColor(Color.WHITE);
}
});
Use OnClickListeners to change the background of the Button using setBackgroundColor() or setBackgroundDrawable()
You can use a CheckBox for your button and set the background to a state list drawable that tests for the android:state_checked
attribute.
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
button1.setOnClickListeners(new OnClickListener() {
public void onClick(View v) {
button1.setBackgroundColor(Color.RED);
}
});
button2.setOnClickListeners(new OnClickListener() {
public void onClick(View v) {
button1.setBackgroundColor(Color.WHITE);
}
});
What you want is a state list. A quick Google found this article: http://blog.androgames.net/40/custom-button-style-and-theme/ that explains them step by step. That way you don't need any code :)
Here's a code that you need to save as an .xml file and place into your drawable folder.
The android:drawable
tags point to the drawable resources for each button state. You can shorten this list if you want to.
Then you can use it as a drawable when creating your layout.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_window_focused="false" android:state_enabled="true"
android:drawable="@drawable/menu_button_normal" />
<item android:state_window_focused="false" android:state_enabled="false"
android:drawable="@drawable/menu_button_normal" />
<item android:state_pressed="true" android:drawable="@drawable/menu_button_pressed" />
<item android:state_enabled="true" android:drawable="@drawable/menu_button_normal" />
<item android:state_enabled="false" android:drawable="@drawable/menu_button_normal"/>
</selector>
精彩评论