实现效果如图所示:
实现效果相关属性
android:showText:设置on/off的时候是否显示文字,boolean
android:splitTrack:是否设置一个间隙,让滑块与底部图片分隔,boolean
android:switchMinWidth:设置开关的最小宽度
android:switchPadding:设置滑块内文字的间隔
android:switchTextAppearance:设置开关的文字外观,暂时没发现有什么用…
android:textOff:按钮没有被选中时显示的文字
android:textOn:按钮被选中时显示的文字
android:textStyle:文字风格,粗体,斜体写划线那些
android:track:底部的图片
android:thumb:滑块的图片
1.在代码中布局:
<Switch
android:id="@+id/switch_fingerline"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:checked="true"
android:thumb="@drawable/thumb_selector"
android:track="@drawable/track_selector"
android:theme="@style/SwitchCompat.Control"/>
2.按钮样式
thumb_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/thumb_on" android:state_checked="true"/>
<item android:drawable="@drawable/thumb_off" android:state_checked="false"/>
</selector>
thumb_on.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
android:width="5dp"
android:color="@android:color/transparent" />
<solid android:color="@android:color/white" />
android:width="20dp"
android:height="20dp" />
</shape>
thumb_off.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
android:width="5dp"
android:color="@android:color/transparent" />
<solid android:color="@android:color/white" />
android:width="20dp"
android:height="20dp" />
</shape>
track_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/track_on" android:state_checked="true"/>
<item android:drawable="@drawable/track_off" android:state_checked="false"/>
</selector>
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="@color/maincolor" />
<corners android:radius="20dp"/>
</shape>
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="#AAA" />
<corners android:radius="20dp" />
</shape>
3.开关监控回调:
switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(!buttonView.isPressed()){ // 每次 setChecked 时会触发onCheckedChanged 监听回调,而有时我们在设置setChecked后不想去自动触发 onCheckedChanged 里的具体操作, 即想屏蔽掉onCheckedChanged;加上此判断
return;
}
}
});
--------END------
我是静染星辰,私人微信:azxy986753
欢迎添加微信,互相学习,互相进步!
网友评论