Android: 使用XML指定ToggleButton的两个不同图像

100

我试图覆盖默认的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 -->

但是这并不起作用;阅读ToggleButtonAPI (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 - Timmmm
1
不要理会那个; CompoundButton 是抽象的! - Timmmm
1个回答

159

你的代码没问题。然而,切换按钮会显示与其匹配的选择器中的第一项,因此默认应该放在最后。按照以下方式排列项目,以确保它们都能被使用:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:state_pressed="true" /> //currently pressed turning the toggle on
    <item android:state_pressed="true" /> //currently pressed turning the toggle off
    <item android:state_checked="true" /> //not pressed default checked state
    <item /> //default non-pressed non-checked
</selector>

3
非常有道理,我从来没有将选择器和开关语句联系起来。 - I82Much
你让我的一天变得美好了…我在按钮、复选框方面遇到了问题,后来也尝试了单选按钮,最终这篇文章对我很有帮助。非常感谢 Vitaly Polonetsky 和 I82Much。 - David Prun
8
文档中说它从顶部开始读取,停在第一个满足所有条件的状态,所以如果默认状态在顶部,它将永远无法通过该可绘制对象。 - Travis
1
@I82Much,使用switch语句可以无论顺序如何都能选择“正确的”选项,这更像是一个带有条件的冗长的if-elseif-elseif-else语句,例如state_x == true && state_y == false && state_z = true - TWiStErRob

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接