ToggleButton 滑动开关
项目概述
滑动开关是一个纯粹的自定义控件,上面的按钮会随着我们的左右滑动而滑动,并且在状态改变时通知用户,效果如下图1-9 所示,这也是应用中设置某些状态信息时最常见的控件,因此,我们有必要学习关于如何
自定义一个这样的滑动开关。
滑动开关UI
布局文件为activity_main.xml,代码如下:res/layout/activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:itheima="http://schemas.android.com/apk/res/com.itheima.togglebuttondemo"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.itheima.togglebuttondemo.view.ToggleButton
android:id="@+id/togglebutton"
android:layout_width="wrap_content"
android:layout_centerInParent="true"
itheima:SwitchBtnBackgroud="@drawable/switch_background"
itheima:SlidBtnBackgroud="@drawable/slide_button_background"
itheima:CurrentState="false"
android:layout_height="wrap_content"/>
</RelativeLayout>
在activity_main.xml 布局中引入如下命名空间:
xmlns:itheima=”http://schemas.android.com/apk/res/com.itheima.togglebuttondemo”,com.itheima.togglebuttondemo 是包名,itheima 是自定义的命名控件名,可以任取名字,也可以使用类名。
上面的布局主要是引入com.itheima.togglebuttondemo.view.ToggleButton 类和自定义属性的使用。添加自定义属性,在values 目录下创建attrs.xml 文件,具体代码如文件所示:res/values/attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ToggleButton">