项目需求,本来想找网上的直接用,但是自己也不是太忙,就说自己写下吧。用了一上午的时间调试出来了基本的效果:
原理:
通过自定义View来进行按钮的绘制。
知识点:
(1)继承view,实现构造方法,熟练使用onDraw(Canvas canvas)方法
(2)需要三种图片,活动按钮,还有开关背景
(3)需要熟悉onTouch方法的使用
(4)了解onMeasure(int widthMeasureSpec, int heightMeasureSpec)方法
这样就基本够了
所以的操作基本上都在onTouch以及onDraw中
在onTouch中获取当前手指的坐标的x的值,
在onDraw中通过计算来进行背景的绘制,以及滑块的位置
<pre name="code" class="java">@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Matrix matrix = new Matrix(); Paint paint = new Paint(); float det = 0; if (mCurrentX > bg_off.getWidth()/2) { canvas.drawBitmap(bg_on, matrix, paint); }else { canvas.drawBitmap(bg_off, matrix, paint); } if (isScroll) { if (mCurrentX >= bg_on.getWidth()/2) { det = bg_on.getWidth() - bg_contral.getWidth(); }else if (mCurrentX < 0 ) { det = 0; }else{ det = mCurrentX; } }else { if (mCurrentX >= bg_on.getWidth() ) { det = bg_on.getWidth() - bg_contral.getWidth(); }else if (mCurrentX < 0 ) { det = 0 ; }else { det = mCurrentX; } } //画出滑块 canvas.drawBitmap(bg_contral, det , 0, paint); }
onTouch:
<pre name="code" class="java">@Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mCurrentX = (int)event.getX(); break; case MotionEvent.ACTION_MOVE: isScroll = true; mCurrentX = (int)event.getX(); break; case MotionEvent.ACTION_UP: isScroll = false; mCurrentX = (int)event.getX(); break; default: break; } invalidate(); return true; }
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int specModeHeight = MeasureSpec.getMode(heightMeasureSpec); int specSizeHeight = MeasureSpec.getSize(heightMeasureSpec); Log.e("HJJ", "****specModeHeight:" + specModeHeight + ", specSizeHeight:" + specSizeHeight ); int widthSize = MeasureSpec.getSize(bg_on.getWidth()); int heightSize = MeasureSpec.getSize(bg_on.getHeight()); setMeasuredDimension(widthSize, heightSize); }
demo:http://download.csdn.net/detail/u012808234/9107871