废话少说,上图
关闭状态:
开启状态:
首先这里我使用了Switch控件(自行百度)
下面上代码:
<Switch
android:id="@+id/open_h"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_centerHorizontal="true"
android:layout_marginRight="20dp"
android:thumb="@drawable/thumb_selector"
android:track="@drawable/track_selector"
/>
thumb_selector:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<size
android:width="20dp"
android:height="20dp">
</size>
<!-- 填充的颜色:这里设置滑动块为白色 -->
<solid android:color="@color/white" />
<!--<solid android:color="@color/theme_color" />-->
****<!-- 边框的颜色 :因为需要显示一点点背景色,所以设置了一个透明边框 -->**
<stroke
android:width="2dp"
android:color="@android:color/transparent" />**
<!--<corners android:radius="2dip" />-->
<corners android:radius="2dip" />
</shape>
track_selector:
<?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 version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid
android:color="#3087ea">
</solid>
<corners android:radius="12dp" />
</shape>
track_off:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!--<size-->
<!--android:width="60dp"-->
<!--android:height="35dp">-->
<!--</size>-->
<solid
android:color="@android:color/darker_gray">
</solid>
<corners android:radius="12dp" />
</shape>
好了大功告成,下面我们开始监听这个控件的状态
open.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b){
Log.d("switch++", "onCheckedChanged: 选中");
}else {
Log.d("switch++", "onCheckedChanged: 没有选中");
}
}
});
}
这就彻底完成了,点个赞好吗,秋梨膏!!!