自定义view实现开关按钮并监听(有滑动效果)
原理:其实是首先得有两张图片,一张是背景图,左开右关,第二张其实说白了就是挡住某一边的图,所以这张图的宽度就只有第一张的一半,这样就可以让用户辨别按钮是开还是关。然后监听view的点击事件,从而调用invalidate()方法来重绘来产生滑动效果。
难点:得从点击事件获取滑动的坐标然后调整第二张图片离左边的距离。
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
maxLeft = toggleBackground.getWidth() - toggleSolide.getWidth();
canvas.drawBitmap(toggleBackground, 0, 0, paint);
switch (state) {
case STATE_DOWN:
case STATE_MOVE:
if (currentX > toggleSolide.getWidth() / 2f) {
// 让滑块向右移动(重新绘制滑块的位置)
left = currentX - toggleSolide.getWidth() / 2f;
if (left > maxLeft)
left = maxLeft;
canvas.drawBitmap(toggleSolide, left, 0, paint);
} else if (currentX <= toggleSolide.getWidth() / 2f) {
// 让滑块不动就可以
canvas.drawBitmap(toggleSolide, 0, 0, paint);
}
break;
case STATE_NONE:
if (toggleBackground != null) {
canvas.drawBitmap(toggleBackground, 0, 0, paint);
}
if (toggleSolide != null) {
canvas.drawBitmap(toggleSolide, 0, 0, paint);
}
break;
case STATE_UP:
if (isOpen) {
canvas.drawBitmap(toggleSolide, maxLeft, 0, paint);
} else {
canvas.drawBitmap(toggleSolide, 0, 0, paint);
}
if(onUpActionListenter!=null){
onUpActionListenter.OnUp(isOpen);
}
break;
default:
canvas.drawBitmap(toggleSolide, 0, 0, paint);
break;
}
}
开关的监听:通过自定义接口来实现对开关的监听,并在点击事件调用接口方法
private OnUpActionListenter onUpActionListenter;
public interface OnUpActionListenter{
public void OnUp(boolean isOpen);
}
public void setOnUpActionListenter(OnUpActionListenter listenter){
this.onUpActionListenter = listenter;
}