我试图覆盖默认的ToggleButton
外观。下面是定义ToggleButton
的XML:
<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_checked属性。
那么,在XML中是否有一种实现我想要的功能的方法,或者我只能使用我的混乱解决方案?
CompoundButton
。 - TimmmmCompoundButton
是抽象的! - Timmmm