更具项目需求,我需要写一个自定义的选择器, 自己写有底气,用系统的togglebutton。。。。。。我宣简洁的啦(台湾腔读)··········
下面是我写的自定义控件:
注意:当设置回调函数的时候,要判断接口是否是null,因为如果不判断的话,会出很多问题。
如在activity中使用该控件,app会直接死掉。fragment中使用该控件的话,会直接导致fragment重新加载。。。。
最关键的是 手机啥信息都不会反馈给你 。。泪奔
public class ToggleButton extends View { private Bitmap backgroundPic = null; private Bitmap slideBtn; private Paint paint; private float slideBtn_letf = 0; private static boolean currentState = false ;//开关状态 true为打开 private boolean isDrag = false; //是否是拖拽 private OnToggleStateChangedListener onToggleStateChangedListener = null; public boolean isCurrentState() { return currentState; } public void setCurrentState(boolean currentState) { this.currentState = currentState; } public ToggleButton(Context context, AttributeSet attrs) { super(context, attrs); initView(); } private void initView() { backgroundPic = BitmapFactory.decodeResource(getResources() , R.mipmap.switch_background); slideBtn = BitmapFactory.decodeResource(getResources() ,R.mipmap.slide_button); paint = new Paint(); paint.setAntiAlias(true); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(backgroundPic.getWidth() ,backgroundPic.getHeight()); } @Override protected void onDraw(Canvas canvas) { canvas.save(); canvas.drawBitmap(backgroundPic , 0 , 0 , paint); canvas.drawBitmap(slideBtn , slideBtn_letf , 0 , paint); canvas.restore(); } private void flushState(){ if(currentState){ slideBtn_letf = backgroundPic.getWidth() - slideBtn.getWidth(); }else{ slideBtn_letf = 0; } // onToggleStateChangedListener.getCurrentState(currentState); invalidate(); } private void flushView(){ //对slideBtn的值进行判断,确保其在合理的位置 int maxLeft = backgroundPic.getWidth() - slideBtn.getWidth(); slideBtn_letf = (slideBtn_letf > 0) ? slideBtn_letf : 0; slideBtn_letf = (slideBtn_letf < maxLeft) ? slideBtn_letf :maxLeft; // invalidate(); } private int firstX; private int lastX; @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: lastX = firstX = (int) event.getX(); isDrag = false; break; case MotionEvent.ACTION_MOVE: if(Math.abs(event.getX() - firstX) > 5){ int dis = (int) (event.getX() - lastX); slideBtn_letf += dis; isDrag = true; } break; case MotionEvent.ACTION_UP: int maxLetf = backgroundPic.getWidth() - slideBtn.getWidth(); if(slideBtn_letf > maxLetf /2){ currentState = true; if(onToggleStateChangedListener != null){ onToggleStateChangedListener.getCurrentState(currentState); } }else{ currentState = false; if(onToggleStateChangedListener != null){ onToggleStateChangedListener.getCurrentState(currentState); } } flushState(); break; } flushView(); return true; } public interface OnToggleStateChangedListener{ public void getCurrentState(boolean currentState); } public void setOnToggleStateChangeListener(OnToggleStateChangedListener onToggleStateChangeListener){ this.onToggleStateChangedListener = onToggleStateChangeListener; } }