代码之家  ›  专栏  ›  技术社区  ›  I82Much

android:使用xml为togglebutton指定两个不同的图像

  •  99
  • I82Much  · 技术社区  · 16 年前

    我正试图改写默认值 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 -->
    

    但这不起作用;阅读 按钮开关 原料药(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中想要的,或者我是否陷入了混乱的解决方案中?

    1 回复  |  直到 12 年前
        1
  •  159
  •   m_vitaly    12 年前

    你的密码没问题。但是,切换按钮将显示选择器中与其匹配的第一个项目,因此默认值应排在最后。按以下方式安排项目,以确保所有项目都得到利用:

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