一、废话不多说,先上图
二、实现思路
如果你们的效果要求不是太严苛,你可以使用这种方式。看起来还是挺美观和漂亮的。
1、使用系统的Switch控件,然后设置thumb和track背景就能实现
2、然后监听setOnCheckedChangeListener就能知道打开和关闭
三、代码
activity.xml
<Switch
android:id="@+id/activity_setServe_switch_open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff=""
android:layout_marginTop="100dp"
android:layout_marginLeft="100dp"
android:textOn=""
android:thumb="@drawable/switch_thumb"
android:track="@drawable/switch_track" />
switch_thumb.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<size
android:width="30dp"
android:height="30dp">
</size>
<solid
android:color="@android:color/white">
</solid>
</shape>
switch_track.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_checked="true"
android:drawable="@drawable/switch_track_on"/>
<item
android:state_checked="false"
android:drawable="@drawable/switch_track_off"/>
</selector>
switch_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="#e4e4e4">
</solid>
<corners
android:radius="30dp">
</corners>
</shape>
switch_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="#00ABEC">
</solid>
<corners
android:radius="32dp">
</corners>
</shape>
最后设置监听事件
((Switch)findViewById(R.id.activity_setServe_switch_open)).
setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Toast.makeText(MainActivity.this,"打开",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this,"关闭",Toast.LENGTH_LONG).show();
}
}
});