package com.gxa.custom; 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; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; public class Customtoggle extends View implements OnClickListener,OnTouchListener { private Paint paint; private Bitmap backBitmap,slideBitmap; private float slideLeft,slideMax; //slideLeft:slideBitmap左侧的位置,slideMax:slideBitmap滑动的最大距离 private boolean isOpen;//开关的状态 private boolean isDrag;//是否滑动 public Customtoggle(Context context, AttributeSet attrs) { this(context, attrs,0); } public Customtoggle(Context context) { this(context,null); } public Customtoggle(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(backBitmap.getWidth(), backBitmap.getHeight()); } private void init() { paint = new Paint(); paint.setAntiAlias(true); backBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.togglebutton_background); slideBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.togglebutton_slide); slideMax = backBitmap.getWidth()-slideBitmap.getWidth(); setOnClickListener(this); setOnTouchListener(this); } @Override protected void onDraw(Canvas canvas) { canvas.drawBitmap(backBitmap, 0, 0, paint); canvas.drawBitmap(slideBitmap, slideLeft, 0, paint); } /** * ontouch 返回值的问题 * true 当前的触摸事件被消耗 * false 当前的触摸事件没有被消耗 分发出去了 activity ontouchevent */ private float firstX; //触摸的初始点 private float preX;//上一次触摸的坐标 @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: isDrag = false; firstX = event.getX(); preX = firstX; break; case MotionEvent.ACTION_MOVE: if (Math.abs(event.getX()-firstX)>5) { isDrag = true; } float distance = event.getX() - preX; //滑动的距离 slideLeft+=distance; preX = event.getX(); flushView(); break; case MotionEvent.ACTION_UP: if (isDrag) { if (slideLeft>slideMax/2) { isOpen = true; }else{ isOpen = false; } flushStatus(); } break; } return false; } private void flushStatus() { if (isOpen) { slideLeft = slideMax; }else{ slideLeft = 0; } invalidate(); } private void flushView() { slideLeft = (slideLeft>=0)?slideLeft:0; slideLeft = (slideLeft<=slideMax)?slideLeft:slideMax; invalidate(); } @Override public void onClick(View v) { if (!isDrag) { isOpen = !isOpen; flushStatus(); } } }
时间: 2024-11-13 08:09:33