100

我正在尝试覆盖默认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"/>

现在,我们有两个 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. 

There does not seem to be the android:state_checked attribute, despite the class having the method isChecked() and setChecked().

So, is there a way to do what I want in XML, or am I stuck with my messy workaround?

4

1 回答 1

159

Your code is fine. However, the toggle button will display the first item in your selector that it matches, so the default should come last. Arrange the items in the following manner to ensure they will all be utilized:

<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>
于 2009-10-07T18:37:27.310 回答