先看下效果图
自定义View
public class Seniorswitch extends Switch {
/**
* 监听是否存在动作
*/
private boolean IF_EVENT_MOVE = false;
/**
* 监听滑动时间
*/
private long MOVE_TIME = -1;
public Seniorswitch(Context context) {
super(context);
}
public Seniorswitch(Context context, AttributeSet attrs) {
super(context, attrs);
}
public Seniorswitch(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (IF_EVENT_MOVE && ev.getAction() == MotionEvent.ACTION_UP) {
MOVE_TIME = -1;
IF_EVENT_MOVE = false;
if (ev.getX() <= getWidth() / 2) {
setChecked(false);
} else {
setChecked(true);
}
} else if (ev.getAction() == MotionEvent.ACTION_UP) {
//松开
IF_EVENT_MOVE = false;
MOVE_TIME = -1;
} else if (ev.getAction() == MotionEvent.ACTION_MOVE) {
//动作
if (MOVE_TIME == -1) {
MOVE_TIME = System.currentTimeMillis();
} else {
if (System.currentTimeMillis() - MOVE_TIME > 500) {
IF_EVENT_MOVE = true;
}
}
}
return super.onTouchEvent(ev);
}
}
再上switch_selector.xml文件
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true">
<shape android:shape="oval">
<!--背景色-->
<solid android:color="#ffffff" />
<!--边框-->
<stroke android:width="@dimen/dp_2" android:color="#00000000" />
<!--大小-->
<size android:width="@dimen/dp17" android:height="@dimen/dp17" />
</shape>
</item>
<item android:state_checked="false">
<shape android:shape="oval">
<!--背景色-->
<solid android:color="#ffffff" />
<!--边框-->
<stroke android:width="@dimen/dp_2" android:color="#00000000" />
<!--大小-->
<size android:width="@dimen/dp17" android:height="@dimen/dp17" />
</shape>
</item>
</selector>
再上switch_track_selector.xml文件
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true">
<shape android:shape="rectangle">
<solid android:color="#1E7AFA" />
<!--圆角-->
<corners android:radius="@dimen/dp9" />
<!--大小-->
<size android:width="@dimen/dp19" android:height="@dimen/dp19" />
</shape>
</item>
<item android:state_checked="false">
<shape android:shape="rectangle">
<solid android:color="#7E8187" />
<!--圆角-->
<corners android:radius="@dimen/dp9" />
<!--大小-->
<size android:width="@dimen/dp19" android:height="@dimen/dp19" />
</shape>
</item>
</selector>
xml布局中引用
<com.xx.xx.xx.xx.Seniorswitch
android:id="@+id/switch_lock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="17dp"
android:background="#00000000"
android:checked="false"
android:thumb="@drawable/switch_selector"
android:track="@drawable/switch_track_selector" />
Java代码中使用
switch_bt.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
} else {
}
}
});
结束!