天天看点

自定义控件之自定义开关

package com.example.toggleview;

import com.example.defineview.R;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * Android界面绘制流程 测量 摆放 绘制 measure layout draw onMeasure onLayout onDraw
 * 重写这些方法,实现自定义控件 都在onResume()之后执行
 * 
 * View流程 onMeasure()(在这个方法里指定自己的宽高)->onDraw()(绘制自己的内容)
 * 
 * ViewGroup流程 onMeasure()(指定自己的宽高,所有子view的宽高)->onLayout()(摆放所有子View)
 * ->onDraw()(绘制内容)
 * 
 */
public class ToggleView extends View {

	private Paint paint;
	private Bitmap backgroundBitmap;
	private Bitmap slideButton;
	private Boolean isSwitch = false;
	private Boolean isTouchMode = false;
	private int currentX;
	private int widthX;

	public ToggleView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		init();
	}

	public ToggleView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public ToggleView(Context context) {
		super(context);
		init();
	}

	private void init() {
		paint = new Paint();
		backgroundBitmap = BitmapFactory.decodeResource(getResources(),
				R.drawable.switch_background);
		slideButton = BitmapFactory.decodeResource(getResources(),
				R.drawable.slide_button);

	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		// TODO Auto-generated method stub
		setMeasuredDimension(backgroundBitmap.getWidth(),
				backgroundBitmap.getHeight());
	}

	@Override
	protected void onDraw(Canvas canvas) {
		canvas.drawBitmap(backgroundBitmap, 0, 0, paint);
		if (isTouchMode) {
			float newLeft = currentX - slideButton.getWidth() / 2;
			if (newLeft < 0) {
				newLeft = 0;
			} else if (newLeft > backgroundBitmap.getWidth()
					- slideButton.getWidth()) {
				newLeft = backgroundBitmap.getWidth() - slideButton.getWidth();
			}
			canvas.drawBitmap(slideButton, newLeft, 0, paint);

		} else {
			if (!isSwitch) {
				canvas.drawBitmap(slideButton, 0, 0, paint);
			} else {
				canvas.drawBitmap(slideButton, backgroundBitmap.getWidth()
						- slideButton.getWidth(), 0, paint);
			}

		}

		super.onDraw(canvas);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			currentX = (int) event.getX();
			isTouchMode = true;
			break;
		case MotionEvent.ACTION_MOVE:
			currentX = (int) event.getX();
			break;
		case MotionEvent.ACTION_UP:
			currentX = (int) event.getX();
			widthX = backgroundBitmap.getWidth() / 2;
			if (currentX < widthX) {
				isSwitch = false;
			}else if(currentX > widthX){
				isSwitch = true;
			}
			isTouchMode = false;
			break;

		default:
			break;
		}
		
		invalidate();
		return true;
	}

}
           

继续阅读