动手写自定义控件系列:开关效果

/**
* Created by renhe on 15/12/22.
* <p/>
* 1.理解自定义控件的原理:
* 控件都是继承自View,通过重写相关方法来实现新的效果。一般来讲,通过继承已有的控件来实现自定义效果会简单一些。
* <p/>
* 一个View从创建到显示的步骤:
* a.执行View构造方法,创建对象
* b. 测量View: onMeasure(int,int),执行的是setMeasuredDimension(int,int)这个方法
* c.指定View的位置: onLayout(boolean,int,int,int,int) 这个方法只有自定义ViewGroup才用得到
* d.绘制View的内容: onDraw(canvas)
* <p/>
* 2.实现简单的自定义效果:
*/
实现效果:

background_bitmap:

slide_bitmap: 

 实现效果:当前只实现了点击切换显示开和关,后面研究了会增加滑动实现开关的切换。


public class MyToggleButton extends View implements View.OnClickListener {

    private Paint paint;
    private Bitmap backgroundBitmap;
    private Bitmap slideBitmap;
    private float slideLeft; // 距离左边的距离
    private boolean currentStatus = false; // 开关当前状态

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        // 当前View的测量大小
        setMeasuredDimension(backgroundBitmap.getWidth(), backgroundBitmap.getHeight());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawBitmap(backgroundBitmap, 0, 0, paint);
        canvas.drawBitmap(slideBitmap, slideLeft, 0, paint);
    }

    /**
     * 代码中实例化控件时使用
     */
    public MyToggleButton(Context context) {
        super(context);
        initView();
    }

    private void initView() {
        paint = new Paint();
        paint.setColor(Color.RED);
        paint.setAntiAlias(true);  // 设置使让边缘圆滑

        backgroundBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.bg_bitmap);
        slideBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.slide_bitmap);

        setOnClickListener(MyToggleButton.this);

    }

    /**
     * 布局中使用
     */
    public MyToggleButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    /**
     * 默认显示样式的时候使用
     */
    public MyToggleButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    @Override
    public void onClick(View v) {
        currentStatus = !currentStatus;
        if (currentStatus) {
            slideLeft = backgroundBitmap.getWidth() - slideBitmap.getWidth();
        } else {
            slideLeft = 0;
        }

        invalidate(); // 刷新View,重新执行onDraw()方法
    }
}

布局代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <renhe.myapplication.MyToggleButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

</RelativeLayout>

 

posted @ 2015-12-22 23:13  zero_7  阅读(204)  评论(0编辑  收藏  举报