自定义控件:滑动开关

本文详细介绍了如何实现一个自定义的滑动开关控件,包括项目概述、滑动开关UI设计、业务逻辑实现以及知识点总结。在UI部分,展示了布局文件activity_main.xml的编写,同时讲解了自定义属性的设置。在业务逻辑部分,讨论了自定义控件的触摸事件处理和重新绘制机制。最后,总结了自定义控件过程中关键的setMeasuredDimension、invalidate和onTouchEvent方法的应用。
摘要由CSDN通过智能技术生成

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">
        
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值