Android UI之switch的thumb与track属性定制自己的switch

来源:互联网 发布:如何练出完美胸肌知乎 编辑:程序博客网 时间:2024/05/16 05:52

利用官方的switch控件的thumb与track属性,可以自定义自己的switch,实例如下:

上面的switch是官方默认的形状,下面的是通过设定自定义的thumb与track来实现的效果。





那如何来实现呢?

1.thumb比较好实现,利用XML来定义一个drawable文件,命名为switch_thumb

<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"    android:shape="oval">    <size        android:width="30dp"        android:height="30dp">    </size>    <solid        android:color="@android:color/white">    </solid></shape>
thumb属性指的是:switch上面滑动的滑块,也就是上图中的白色圆形滑块


2、track属性又该如何设置呢?

问题在于打开switch与关闭switch,switch的下面的滑道应该是不同的颜色,我们想到了可以用drawable的selector标签,利用switch的不同状态,来加载不同的drawable文件。我们查看官方switch文档,发现其有voidsetChecked(boolean checked)

Changes the checked state of this button.

这样一个方法,所以我们可以利用其state_checked状态,依据不同的状态来选择加载不同的drawable文件

1):首先,我们定义一个drawable文件:switch_track_on.xml

<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"    android:shape="rectangle">    <solid        android:color="@android:color/holo_green_light">    </solid>    <corners        android:radius="32dp">    </corners></shape>
           2):再定义一个drawable文件:switch_track_off.xml

<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"    android:shape="rectangle">    <solid        android:color="@android:color/darker_gray">    </solid>    <corners        android:radius="30dp">    </corners></shape>
3):然后定义drawable文件:switch_track.xml

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">    <item        android:state_checked="true"        android:drawable="@drawable/switch_track_on"></item>    <item        android:state_checked="false"        android:drawable="@drawable/switch_track_off"></item></selector>

4):最后在布局文件中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context=".MainActivity">    <Switch        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center_horizontal"        android:layout_weight="1"/>    <Switch        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center_horizontal"        android:thumb="@drawable/switch_thum"        android:track="@drawable/switch_track"        android:layout_weight="1"/></LinearLayout>



注:通过上述方法实现的switch可以基本达到我们的使用要求。

5 0
原创粉丝点击