8

Android 万能开关控件LSwitch - 简书

 4 years ago
source link: https://www.jianshu.com/p/cf7926445ada?
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
0.9982020.04.05 18:33:37字数 479阅读 770

一. 为什么不用系统的Switch 或 目前第三方封装好的SwitchButton

1. 系统的Switch: 容易出现兼容性问题, 低版本的显示样式可能会不同.
2. 系统的Switch: 改样式, 都要新建一个xml文件, 比较麻烦.
3. 第三方SwitchButton: 只是把常见的样式封装起来, 碰到特殊情况无法进行扩展.

github地址: https://github.com/liys666666/LSwitch

二. 先上效果图---常见样式

webp
LSwitch.gif
lswitch2.png

二. 简单使用

1. 导入项目
//项目根目录下 build.gradle
allprojects {
        repositories {
            ...
            maven { url 'https://jitpack.io' } //添加
        }
    }
dependencies {
    implementation 'com.github.liys666666:LSwitch:V1.0.4'  //添加
}
<com.liys.lswitch.LSwitch
        android:id="@+id/lswitch"
        android:layout_width="50dp"
        android:layout_height="30dp"
        app:checked="true"/>

//监听
lswitch.setOnCheckedListener();

1. LSwitch特有属性
app:track_radius="" 背景---圆角
app:track_height="" 背景---高度
app:thumb_radius="" 滑块---圆角
app:thumb_height="" 滑块---高度
app:thumb_width="" 滑块---宽度

2. 公共属性
app:checked="" 是否选中
app:text_show="" 文字是否显示
app:animator_duration="" 滑动--动画时间
打开
app:track_color_off="" 背景---颜色
app:thumb_color_off="" 滑块---颜色
app:text_color_off="" 字体---颜色
app:text_size_off="" 字体---大小
app:text_off="" 字体---内容
关闭
app:track_color_on=""
app:thumb_color_on=""
app:text_color_on=""
app:text_size_on=""
app:text_off=""

每个属性都有对应的set方法 (单位: dp或sp)

三. 如果框架的样式无法满足, 应该如何扩展?

为了方便说明, 举个简单的例子:

lswitch3.png

1. 新建MySwitch 继承 BaseSwitch 或 LSwitch
2. 重写getAnimatorValueOff()和getAnimatorValueOn(), 确定滑动轨迹.
3. 重写onDraw(), 绘制你需要的图形或文字.

public class MySwitch extends BaseSwitch{
    //...省略构造方法

    @Override
    protected float getAnimatorValueOff() {  //滑块打开时的值
        return mHeight-mWidth/2;
    }

    @Override
    protected float getAnimatorValueOn() { //滑块关闭时的值
        return mWidth/2;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //根据个人需要进行绘制
        canvas.drawRoundRect(new RectF(0, 0, mWidth, mHeight), mWidth/2, mWidth/2, paintTrack);
        canvas.drawCircle(mWidth/2, animatorValue, mWidth/2, paintThumb);
    }
}

注意: animatorValue的值
例如:
getAnimatorValueOff()=10
getAnimatorValueOn() = 1
打开时: animatorValue 会从1 慢慢变大到10;
关闭时: animatorValue 会从10 慢慢变大到1;

四. 总结:

1. 对于常见样式, 学习成本低, 直接在xml设置属性即可.
2. 属于半开放框架, 完全可以根据个人的情况, 扩展出属于自己Switch样式.
3. 不足之处: 常见的样式, 没有其它第三方封装的完美. 例如, 阴影, 渐变, 图片等, 不过这些都可以在这个框架基础上进行扩展.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK