Android仿微信滑動(dòng)按鈕功能
首先我們來看一下微信中switchButton的效果, 就是下圖那個(gè)樣子, 打開微信玩一下就知道了

慣例, 先上實(shí)現(xiàn)的效果

接下來, 我就說明如何一步步實(shí)現(xiàn)這個(gè)效果控件。
1.定義背景和中間圓球的顏色
public class SwitchButton extends View {public SwitchButton(Context context) {this(context, null);}public SwitchButton(Context context, @Nullable AttributeSet attrs) {this(context, attrs, 0);}public SwitchButton(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SwitchView, defStyleAttr, R.style.def_switch_view);int indexCount = typedArray.getIndexCount();for (int i = 0; i < indexCount; i++) {int attr = typedArray.getIndex(i);switch (attr) {case R.styleable.SwitchView_switch_bg_color://背景顏色switchViewBgColor = typedArray.getColor(attr, Color.BLACK);break;case R.styleable.SwitchView_switch_ball_color://圓球顏色switchViewBallColor = typedArray.getColor(attr, Color.BLACK);break;}}typedArray.recycle();initData();}}
在這里, 背景顏色和圓球顏色是從自定義屬性中取的, 如果沒有定義, 就取默認(rèn)的顏色。
2.初始化一些東西, 比如創(chuàng)建兩個(gè)畫筆
private void initData() {mBallPaint = createPaint(switchViewBallColor, 0, Paint.Style.FILL, 0);mBgPaint = createPaint(switchViewBgColor, 0, Paint.Style.FILL, 0);...}
3.在onSizeChanged方法里定義一些長(zhǎng)度和寬度
protected void onSizeChanged(int w, int h, int oldw, int oldh) {mViewHeight = h;mViewWidth = w;// 默認(rèn)描邊寬度是控件寬度的1/30, 比如控件寬度是120dp, 描邊寬度就是4dpswitchViewStrockWidth = w * 1.0f / 30;mStrokeRadius = mViewHeight / 2;mSolidRadius = (mViewHeight - 2 * switchViewStrockWidth) / 2;BALL_X_RIGHT = mViewWidth - mStrokeRadius;mSwitchBallx = mStrokeRadius;mBgStrokeRectF = new RectF(0, 0, mViewWidth, mViewHeight);}
在這里, 定義了圓球的半徑, 圓球中心的初始x坐標(biāo), 和用來畫圓角矩形的矩形, 特別注意這里的switchViewStrockWidth指的是如下圖這段

4.在onMeasure方法里定義控件的寬度和高度
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {super.onMeasure(widthMeasureSpec, heightMeasureSpec);int widthMode = MeasureSpec.getMode(widthMeasureSpec);int heightMode = MeasureSpec.getMode(heightMeasureSpec);int measureWidth;int measureHeight;switch (widthMode) {case MeasureSpec.UNSPECIFIED:case MeasureSpec.AT_MOST://wrap_contentmeasureWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DEF_W, getResources().getDisplayMetrics());widthMeasureSpec = MeasureSpec.makeMeasureSpec(measureWidth, MeasureSpec.EXACTLY);break;case MeasureSpec.EXACTLY:break;}switch (heightMode) {case MeasureSpec.UNSPECIFIED:case MeasureSpec.AT_MOST://wrap_contentmeasureHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DEF_H, getResources().getDisplayMetrics());heightMeasureSpec = MeasureSpec.makeMeasureSpec(measureHeight, MeasureSpec.EXACTLY);break;case MeasureSpec.EXACTLY:break;}super.onMeasure(widthMeasureSpec, heightMeasureSpec);}
這里默認(rèn)高是60dp, 高是120dp, 自己定義時(shí)最好也按照這個(gè)比例, 否則會(huì)顯得不和諧
5.這里是最重要的, 在onDraw方法里畫背景和圓球
@Overrideprotected void onDraw(Canvas canvas) {drawSwitchBg(canvas);drawSwitchBall(canvas);}private void drawSwitchBall(Canvas canvas) {canvas.drawCircle(mSwitchBallx, mStrokeRadius, mSolidRadius, mBallPaint);}private void drawSwitchBg(Canvas canvas) {canvas.drawRoundRect(mBgStrokeRectF, mStrokeRadius, mStrokeRadius, mBgPaint);}
到這里的時(shí)候, 就能看到畫好的背景和圓球了, 但卻是靜態(tài)的, 還不能動(dòng)
6.定義枚舉變量, 用來記錄開關(guān)的狀態(tài)
private enum State {OPEN, CLOSE}private State mCurrentState;
7.當(dāng)button被點(diǎn)擊時(shí), 改變圓球的x坐標(biāo)和背景畫筆的顏色, 調(diào)用invalidate重繪界面
設(shè)置點(diǎn)擊事件
private void initData() {...setOnClickListener(this);}
在 onClick方法里
public void onClick(View v) {mCurrentState = (mCurrentState == State.CLOSE ? State.OPEN : State.CLOSE);//綠色 #1AAC19//灰色 #999999if (mCurrentState == State.CLOSE) {animate(BALL_X_RIGHT, mStrokeRadius, greenColor, greyColor);} else {animate(mStrokeRadius, BALL_X_RIGHT, greyColor, greenColor);}if (mOnCheckedChangeListener != null) {if (mCurrentState == State.OPEN) {mOnCheckedChangeListener.onCheckedChanged(this, true);} else {mOnCheckedChangeListener.onCheckedChanged(this, false);}}}private void animate(int from, int to, int startColor, int endColor) {ValueAnimator translate = ValueAnimator.ofFloat(from, to);translate.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {public void onAnimationUpdate(ValueAnimator animation) {mSwitchBallx = ((float) animation.getAnimatedValue());postInvalidate();}});ValueAnimator color = ValueAnimator.ofObject(new ColorEvaluator(), startColor, endColor);color.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {public void onAnimationUpdate(ValueAnimator animation) {switchViewBgColor = ((int) animation.getAnimatedValue());mBgPaint.setColor(switchViewBgColor);postInvalidate();}});AnimatorSet animatorSet = new AnimatorSet();animatorSet.playTogether(translate, color);animatorSet.setDuration(200);animatorSet.addListener(new AnimatorListenerAdapter() {public void onAnimationStart(Animator animation) {setClickable(false);}public void onAnimationEnd(Animator animation) {setClickable(true);}});animatorSet.start();}
需要說明的是, 這里的難點(diǎn)在于如何讓圓球和x坐標(biāo)在指定時(shí)間內(nèi)圓滑地變換到另一個(gè)值, 以及如何讓顏色如何從灰色圓滑地變換到綠色。這里我使用的是值動(dòng)畫(因?yàn)闀簳r(shí)沒有想到更好的方法)。坐標(biāo)值的變換比較簡(jiǎn)單。顏色變化這里用到了估值器ArgbEvaluator
8.暴露接口獲取開關(guān)的狀態(tài)
這里我就不貼代碼了, 很簡(jiǎn)單的
需要源碼的童鞋公眾號(hào)回復(fù):"切換按鈕"即可獲取哦!
到這里就結(jié)束啦
評(píng)論
圖片
表情
