我有一个切换按钮,按下时我想改变它的背景。我的目标是即使在按下事件后将按钮的颜色更改为新颜色。再次按下时,它会进入初始状态。
我使用了以下代码,但在我的情况下,“Press”事件后颜色不会保留。按下按钮时,颜色会发生变化。但是,一旦新闻事件结束,它就会恢复到按钮的原始颜色。
<ToggleButton android:id="@+id/price_activate_button"
android:layout_width="wrap_content"
android:textSize="15dp"
android:text="@string/string_price"
android:layout_alignParentLeft="true"
android:layout_height="wrap_content"
android:background="@drawable/button_blue"
style="@style/ButtonText"
android:textOn="Price"
android:textOff="Price"></ToggleButton>
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true"
android:state_pressed="true">
<shape>
<solid
android:color="#859dbc" />
<stroke
android:width="1dp"
android:color="#859dbc" />
<corners
android:radius="2dp" />
<padding
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp" />
</shape>
</item>
<item android:state_pressed="true" >
<shape>
<solid
android:color="#859dbc" />
<stroke
android:width="1dp"
android:color="#859dbc" />
<corners
android:radius="2dp" />
<padding
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp" />
</shape>
</item>
<item android:state_focused="true" android:state_pressed="false" >
<shape>
<solid
android:color="#2c68e7" />
<stroke
android:width="1dp"
android:color="#2c68e7" />
<corners
android:radius="2dp" />
<padding
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp" />
</shape>
</item>
<item android:state_checked="true">
<shape>
<solid
android:color="#2c68e7" />
<stroke
android:width="1dp"
android:color="#2c68e7" />
<corners
android:radius="2dp" />
<padding
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp" />
</shape>
</item>
<item android:state_checked="false">
<shape>
<solid
android:color="#859dbc" />
<stroke
android:width="1dp"
android:color="#859dbc" />
<corners
android:radius="2dp" />
<padding
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp" />
</shape>
</item>
</selector>
final ToggleButton price_button = (ToggleButton)findViewById(R.id.price_activate_button);
price_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(price_button.isChecked()){
Toast.makeText(getApplicationContext(), "You have chosen: Yes", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "You have chosen: No", Toast.LENGTH_LONG).show();
}
}
});