我正在尝试覆盖默认ToggleButton
外观。这是定义的 XML ToggleButton
:
<ToggleButton android:id="@+id/FollowAndCenterButton"
android:layout_width="30px"
android:layout_height="30px"
android:textOn="" android:textOff="" android:layout_alignParentLeft="true"
android:layout_marginLeft="5px"
android:layout_marginTop="5px" android:background="@drawable/locate_me"/>
现在,我们有两个 30 x 30 的图标要用于单击/未单击状态。现在我们有代码可以根据状态以编程方式更改背景图标:
centeredOnLocation.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (centeredOnLocation.isChecked()) {
centeredOnLocation.setBackgroundDrawable(getResources().getDrawable(R.drawable.locate_me_on));
} else {
centeredOnLocation.setBackgroundDrawable(getResources().getDrawable(R.drawable.locate_me));
}
}
});
显然,我正在寻找一种更好的方法来做到这一点。我试图为背景图像制作一个选择器,它会自动在状态之间切换:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/locate_me" /> <!-- default -->
<item android:state_checked="true"
android:drawable="@drawable/locate_me_on" /> <!-- pressed -->
<item android:state_checked="false"
android:drawable="@drawable/locate_me" /> <!-- unchecked -->
但这不起作用;阅读ToggleButton
API(http://developer.android.com/reference/android/widget/ToggleButton.html),似乎唯一继承的 xml 属性是
XML Attributes
Attribute Name Related Method Description
android:disabledAlpha The alpha to apply to the indicator when disabled.
android:textOff The text for the button when it is not checked.
android:textOn The text for the button when it is checked.
There does not seem to be the android:state_checked attribute, despite the class having the method isChecked()
and setChecked()
.
So, is there a way to do what I want in XML, or am I stuck with my messy workaround?