繁体   English   中英

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

[英]Android: Specify two different images for togglebutton using XML

我试图覆盖默认的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. 

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

那么,有没有办法在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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM