【发布时间】:2010-12-04 17:15:02
【问题描述】:
我正在尝试覆盖默认的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.
似乎没有 android:state_checked 属性,尽管该类具有 isChecked() 和 setChecked() 方法。
那么,有没有办法在 XML 中做我想做的事,还是我被我凌乱的解决方法困住了?
【问题讨论】:
-
注意,如果你不使用文字,我认为使用
CompoundButton可能会更好。 -
忽略它;
CompoundButton是抽象的!
标签: java android xml togglebutton