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

I82*_*uch 99 java xml android togglebutton

我试图覆盖默认ToggleButton外观.这是定义以下内容的XML ToggleButton:

<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"/>
Run Code Online (Sandbox Code Playgroud)

现在,我们有两个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));
            }
        }
});
Run Code Online (Sandbox Code Playgroud)

显然我正在寻找一种更好的方法来做到这一点.我试图为背景图像制作一个选择器,它会自动在状态之间切换:

 <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 -->
Run Code Online (Sandbox Code Playgroud)

但这不起作用; 阅读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. 
Run Code Online (Sandbox Code Playgroud)

似乎没有android:state_checked属性,尽管类有方法isChecked()setChecked().

那么,有没有办法在XML中做我想做的事情,还是我坚持使用凌乱的解决方法?

m_v*_*aly 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>
Run Code Online (Sandbox Code Playgroud)

  • 某个地方的文档说它从顶部读取,停在第一个满足条件的状态,所以如果默认位于顶部,它将永远不会超过那个drawable. (8认同)
  • 这很有道理; 我从未在选择器和switch语句之间建立连接. (3认同)