一. 為什么不用系統(tǒng)的Switch 或 目前第三方封裝好的SwitchButton
1. 系統(tǒng)的Switch: 容易出現(xiàn)兼容性問題, 低版本的顯示樣式可能會(huì)不同.
2. 系統(tǒng)的Switch: 改樣式, 都要新建一個(gè)xml文件, 比較麻煩.
3. 第三方SwitchButton: 只是把常見的樣式封裝起來, 碰到特殊情況無法進(jìn)行擴(kuò)展.
github地址: https://github.com/liys666666/LSwitch
二. 先上效果圖---常見樣式
二. 簡單使用
1. 導(dǎo)入項(xiàng)目
//項(xiàng)目根目錄下 build.gradle
allprojects {
repositories {
...
maven { url 'https://jitpack.io' } //添加
}
}
dependencies {
implementation 'com.github.liys666666:LSwitch:V1.0.4' //添加
}
2.使用
<com.liys.lswitch.LSwitch
android:id="@+id/lswitch"
android:layout_width="50dp"
android:layout_height="30dp"
app:checked="true"/>
//監(jiān)聽
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="" 滑動(dòng)--動(dòng)畫時(shí)間
打開
app:track_color_off="" 背景---顏色
app:thumb_color_off="" 滑塊---顏色
app:text_color_off="" 字體---顏色
app:text_size_off="" 字體---大小
app:text_off="" 字體---內(nèi)容
關(guān)閉
app:track_color_on=""
app:thumb_color_on=""
app:text_color_on=""
app:text_size_on=""
app:text_off=""
每個(gè)屬性都有對應(yīng)的set方法 (單位: dp或sp)
三. 如果框架的樣式無法滿足, 應(yīng)該如何擴(kuò)展?
為了方便說明, 舉個(gè)簡單的例子:
1. 新建MySwitch 繼承 BaseSwitch 或 LSwitch
2. 重寫getAnimatorValueOff()和getAnimatorValueOn(), 確定滑動(dòng)軌跡.
3. 重寫onDraw(), 繪制你需要的圖形或文字.
public class MySwitch extends BaseSwitch{
//...省略構(gòu)造方法
@Override
protected float getAnimatorValueOff() { //滑塊打開時(shí)的值
return mHeight-mWidth/2;
}
@Override
protected float getAnimatorValueOn() { //滑塊關(guān)閉時(shí)的值
return mWidth/2;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//根據(jù)個(gè)人需要進(jìn)行繪制
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
打開時(shí): animatorValue 會(huì)從1 慢慢變大到10;
關(guān)閉時(shí): animatorValue 會(huì)從10 慢慢變大到1;
四. 總結(jié):
1. 對于常見樣式, 學(xué)習(xí)成本低, 直接在xml設(shè)置屬性即可.
2. 屬于半開放框架, 完全可以根據(jù)個(gè)人的情況, 擴(kuò)展出屬于自己Switch樣式.
3. 不足之處: 常見的樣式, 沒有其它第三方封裝的完美. 例如, 陰影, 漸變, 圖片等, 不過這些都可以在這個(gè)框架基礎(chǔ)上進(jìn)行擴(kuò)展.