考虑:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="@drawable/btn_led_on" ></item>
<item android:state_selected="true" android:drawable="@drawable/btn_led_on" ></item>
<item android:drawable="@drawable/btn_led_off"></item>
</selector>
布局中的按钮
<Button
android:id="@+id/main_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/mybutton"
/>
想要在点击时更改背景,但它无法正常工作。
答案 0 :(得分:0)
尝试:
android:state_pressed="true"
这样的事情:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/btn_led_on" android:state_pressed="true"/>
<item android:drawable="@drawable/btn_led_off" android:state_pressed="false"/>
</selector>
修改强> 根据您的要求,请使用此
boolean isButtonClicked=false;
Button button = (Button) findViewById(R.id.main_button);
button.setOnClickListener(new OnClickListener() { // Then you should add add click listener for your button.
@Override
public void onClick(View v) {
if (v.getId() == R.id.main_button) {
isButtonClicked = !isButtonClicked; // toggle the boolean flag
v.setBackgroundResource(isButtonClicked ? R.drawable.btn_led_on : R.drawable.btn_led_off);
}
}
});
答案 1 :(得分:0)
你的选择器应该是这样的:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/numpad_button_bg_selected" android:state_selected="true"></item>
<item android:drawable="@drawable/numpad_button_bg_pressed" android:state_pressed="true"></item>
<item android:drawable="@drawable/numpad_button_bg_normal"></item>
</selector>