Android:使用 XML 为切换按钮指定两个不同的图像

2024-03-10

我正在尝试覆盖默认值ToggleButton外貌。这是定义的 XMLToggleButton:

<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 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() and setChecked().

那么,有没有一种方法可以在 XML 中实现我想要的功能,或者我是否仍坚持使用混乱的解决方法?


你的代码没问题。但是,切换按钮将显示选择器中与其匹配的第一个项目,因此默认值应该排在最后。按以下方式排列物品,以确保它们全部被利用:

<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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android:使用 XML 为切换按钮指定两个不同的图像 的相关文章

随机推荐