【问题标题】:Android: Specify two different images for togglebutton using XMLAndroid:使用 XML 为切换按钮指定两个不同的图像
【发布时间】: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


【解决方案1】:

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

<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>

【讨论】:

  • 这很有意义;我从来没有在选择器和开关语句之间建立联系。
  • 你成就了我的一天...我遇到了按钮、复选框的问题,然后也尝试了单选按钮,最后这篇文章很有帮助。非常感谢 Vitaly Polonetsky 和 ​​I82Much
  • 某处的文档说它从顶部读取,在所有条件都满足的第一个状态处停止,因此如果默认位于顶部,它永远不会超过那个可绘制对象。
  • @I82Much a switch 总是会选择“正确的”而不管顺序如何,这更像是一个冗长的if-elseif-elseif-else,条件为state_x == true &amp;&amp; state_y == false &amp;&amp; state_z = true
猜你喜欢
  • 2012-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-03
  • 2013-07-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多