天天看點

自定義控件之自定義開關

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;
	}

}
           

繼續閱讀