Android 自定义UI状态效果及踩坑记录

发布于 2019-02-28  4 次阅读


前言

有时候我们需要自定义Android的按钮,单选、多选框等具有多种状态的控件。一般的做法是在res目录下编写style的xml文件,本文指出了一些我个人在开发中遇到的一些问题,在此记录一下。

RadioButton 多选按钮

  1. 自定义样式失效
    我们的需求是替换多选按钮未选中及选中时的图片。首次编写了xml文件后,发现选中RadioButton的时候,没有效果变化。
    我们来看看xml代码:
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/ic_xxx" />
    <item android:drawable="@drawable/ic_xxx_press" android:state_checked="true"/>

</selector>

而正确的xml代码应该是这样

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/ic_xxx_press" android:state_checked="true"/>
    <item android:drawable="@drawable/ic_xxx" />

</selector>

注意到了吗?选中(state_checked)一般状态定义的顺序反过来就失效了。
而比较准确的一种定义方法如下:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/ic_xxx"  android:state_checked="false"/>
    <item android:drawable="@drawable/ic_xxx_press" android:state_checked="true"/>

</selector>

这里我们明确了两个item的状态情况,就不会出现上面被覆盖的情况了。
2. 去除多选按钮的圆圈
如果我们要去掉RadioButton的圆圈,那么设置button属性为@null即可,注意是@null,如果写成null就无法编译会报错

 <style name="RadioButton.MainPage" parent="@style/Button">
        <item name="android:maxLines">1</item>
        <item name="android:textSize">10sp</item>
        <item name="android:gravity">center</item>
        <item name="android:layout_weight">1</item>
        <item name="android:paddingTop">2dip</item>
        <item name="android:paddingBottom">2dip</item>
        <item name="android:button">@null</item>
        <item name="android:drawablePadding">2dip</item>
        <item name="android:textColor">@color/greyAdd</item>
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:background">@drawable/s_radius_button_bg</item>
    </style>

后续更新

Comments


来自像素世界的代码家,创造第九艺术!