自定义滑动按钮

今天由于忙,就随便敲了点代码,希望大家见谅。。。

这次实现的是自定义滑动按钮,拖动按钮自动反弹,以及处理点击和触摸事件的冲突等。

附如下代码:

public class MyToggleView extends View implements View.OnClickListener {

	private Bitmap backgroundBitmap;
	private Bitmap slideBitmap;
	private float slideLeft = 0;
	private Paint paint;
	private boolean isClickable = true;

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		// super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		setMeasuredDimension(backgroundBitmap.getWidth(),
				backgroundBitmap.getHeight());
	}

	public MyToggleView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		initView();
	}

	private void initView() {
		backgroundBitmap = BitmapFactory.decodeResource(getResources(),
				R.drawable.switch_background);
		slideBitmap = BitmapFactory.decodeResource(getResources(),
				R.drawable.slide_button);
		paint = new Paint();
		maxLeft = backgroundBitmap.getWidth()-slideBitmap.getWidth();

		
		setOnClickListener(this);
		
	}
	private float startX;
	private float lastX;
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		super.onTouchEvent(event);
		int action = event.getAction();
		switch (action) {
		case MotionEvent.ACTION_DOWN:
			lastX = startX = event.getRawX();
			isClickable = true;
			break;
		case MotionEvent.ACTION_MOVE:
			float newX = event.getRawX();
			float dX = newX - startX;
			if(Math.abs(event.getX()-lastX) >5){
				isClickable = false;
				
			}
				slideLeft += dX;
				flushStatus();
				startX = event.getRawX();
			break;
		case MotionEvent.ACTION_UP:
			if(!isClickable){
				
				if(slideLeft > maxLeft/2){
					state = true;
					slideLeft = maxLeft;
				}else{
					state = false;
					slideLeft = 0;
				}
				flushStatus();
			}
			break;

		default:
			break;
		}
		return true;
	}

	private void flushStatus() {
		if(slideLeft < 0){
			slideLeft = 0;
		}
		if(slideLeft > maxLeft){
			slideLeft = maxLeft;
		}
		invalidate();
	}

	public MyToggleView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initView();
	}

	public MyToggleView(Context context) {
		super(context);
		initView();
	}

	@Override
	protected void onDraw(Canvas canvas) {
		// super.onDraw(canvas);
		canvas.drawBitmap(backgroundBitmap, 0, 0, paint);

		canvas.drawBitmap(slideBitmap, slideLeft, 0, paint);

	}

	private boolean state;
	private float maxLeft;
	@Override
	public void onClick(View v) {
		if(isClickable){
			
			state = !state;
			if(state){
				slideLeft = maxLeft;
			}else{
				slideLeft = 0;
			}
			invalidate();
		} 
	}

}

 

你可能感兴趣的:(android)