自定义控件之开关效果Demo
Button控件是我们经常用到的一种系统控件,由于其样式不怎么美观,很难满足我们的需求,这里我们就需要自定义一个自己想要的Button。
自定义Toggle
思路步骤说明:
- 首先准备两张背景图 :
,
; - 自定义一个类,继承View.重写它的构造方法
- 测量出控件的高宽
- 绘制出控件
- 给控件添加触摸事件,使控件能被拖拽
- 通过接口回调,是控件在开关状态能执行相应的逻辑
代码实现
具体步骤请看代码注释
public class ToggleButton extends View {
private Bitmap mBackground; //按钮背景图
private Bitmap mSlidButton; //滑动层背景图
private int downX; //点击按下的X轴坐标
private int mDistance; //滑动距离距离
private int maxWidth; //能滑动的最大宽度
private OnToggleListener onToggleListener ; //接口的引用
public void setOnToggleListener(OnToggleListener onToggleListener) {
this.onToggleListener = onToggleListener;
}
//获取两张背景图片,初始化能滑动的最大宽度
public ToggleButton(Context context, AttributeSet attrs) {
super(context, attrs);
mBackground = BitmapFactory.decodeResource(getResources(),
R.drawable.switch_background);
mSlidButton = BitmapFactory.decodeResource(getResources(),
R.drawable.slide_button_background);
maxWidth = mBackground.getWidth() - mSlidButton.getWidth();
}
//测量控件的宽高
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(mBackground.getWidth(), mBackground.getHeight());
}
//绘制控件
@Override
protected void onDraw(Canvas canvas) {
// super.onDraw(canvas);
canvas.drawBitmap(mBackground, 0, 0, null);
canvas.drawBitmap(mSlidButton, mDistance, 0, null);
}
//通过触摸事件获取拖拽的距离
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
downX = (int) event.getX(); //获取按下时的水平坐标
break;
case MotionEvent.ACTION_MOVE:
int moveX = (int) event.getX(); //移动后的水平坐标
int dx = moveX - downX; //移动的距离
downX = moveX;
mDistance = mDistance + dx;
//控制拖拽的范围
if (mDistance < 0 ) {
mDistance = 0;
}
if (mDistance > maxWidth) {
mDistance = maxWidth;
}
invalidate(); //重新绘制控制
break;
case MotionEvent.ACTION_UP:
//通过控件移动的位置设置控件的状态
if (mDistance >= maxWidth/2) {
open();
}else {
close();
}
break;
}
return true;
}
//打开状态
private void close() {
mDistance = 0;
invalidate();
if (onToggleListener != null) {
onToggleListener.onClose();
}
}
//关闭状态
private void open() {
mDistance = maxWidth;
invalidate();
if (onToggleListener != null) {
onToggleListener.onOpen();
}
}
//定义接口
public interface OnToggleListener{
public void onClose();
public void onOpen();
}
}
6.在外部引用这个自定义控件
xml布局文件
<com.example.togglebuttondemo.ToggleButton
android:id="@+id/bt_toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ToggleButton toggleButton = (ToggleButton) findViewById(R.id.bt_toggle);
toggleButton.setOnToggleListener(new OnToggleListener() {
@Override
public void onOpen() {
Toast.makeText(MainActivity.this, "Open", Toast.LENGTH_SHORT).show();
}
@Override
public void onClose() {
Toast.makeText(MainActivity.this, "Close", Toast.LENGTH_SHORT).show();
}
});
}