最佳答案
我试图覆盖默认的 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.
尽管该类具有方法 isChecked()
和 setChecked()
,但似乎没有 android: state _ check 属性。
那么,有没有一种方法可以在 XML 中实现我想要的功能,或者我是否被困在了这个混乱的解决方案中?