package com.yuntongxun.ecdemo.common.view; 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 com.yuntongxun.ecdemo.R; /** * Created by yangyang on 4/7/16. * 滑动开关按钮 */ public class SwitchButton extends View implements View.OnClickListener{ private Bitmap switchgreen,switchbottom,switchbutton; private Boolean state=true; private float mcurrentx=0,mlastx=0,dexs=0,countx=0;//当前位置,最后一次位置,移动距离 private OnChangeListener mlistener; private Paint paint; public SwitchButton(Context context) { this(context,null); } public SwitchButton(Context context, AttributeSet attrs) { this(context, null, 0); } public SwitchButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } public Boolean getState() { return state; } public void setState(Boolean state) { this.state = state; } public void init(){ switchbottom= BitmapFactory.decodeResource(getResources(), R.drawable.switchbottom); switchbutton=BitmapFactory.decodeResource(getResources(), R.drawable.switchbutton); switchgreen=BitmapFactory.decodeResource(getResources(), R.drawable.switchgreen); countx=switchbottom.getWidth()-switchbutton.getWidth(); setOnClickListener(this); setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return false; } }); paint=new Paint(); } @Override protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec){ setMeasuredDimension(switchbottom.getWidth(), switchbottom.getHeight()); } @Override protected void onDraw(Canvas canvas){ if(state){ canvas.drawBitmap(switchgreen,0,0,null); canvas.drawBitmap(switchbutton,0,0,null); }else { canvas.drawBitmap(switchbottom,0,0,null); canvas.drawBitmap(switchbutton, countx, 0,null); } } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: mlastx=event.getX(); case MotionEvent.ACTION_MOVE: mcurrentx=event.getX(); dexs=mcurrentx-mlastx; dexs+=dexs; invalidate(); //return true; case MotionEvent.ACTION_UP: if(Math.abs(dexs)>switchbottom.getWidth()/2){ state=!state; } invalidate(); default: break; } invalidate(); return super.onTouchEvent(event); } @Override public void onClick(View v) { //countx = state ?switchbottom.getWidth() - switchbutton.getWidth() : 0; state = !state; if(mlistener != null) { mlistener.OnChange(this,state); } invalidate(); } public void setOnChangeListener(OnChangeListener listener){ mlistener=listener; } public interface OnChangeListener { public void OnChange(SwitchButton sb, Boolean state); } }