github地址:LikeWeChatSwitchButton
首先我們來看一下微信中switchButton的效果, 就是下圖那個樣子, 打開微信玩一下就知道了。
Screenshot_20170404-171429.png
慣例, 先上實(shí)現(xiàn)的效果
switchbutton.gif
接下來, 我就說明如何一步步實(shí)現(xiàn)這個效果控件。
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)建兩個畫筆
private void initData() {
mBallPaint = createPaint(switchViewBallColor, 0, Paint.Style.FILL, 0);
mBgPaint = createPaint(switchViewBgColor, 0, Paint.Style.FILL, 0);
...
}
3.在onSizeChanged方法里定義一些長度和寬度
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mViewHeight = h;
mViewWidth = w;
// 默認(rèn)描邊寬度是控件寬度的1/30, 比如控件寬度是120dp, 描邊寬度就是4dp
switchViewStrockWidth = 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指的是如下圖這段
Paste_Image.png
4.在onMeasure方法里定義控件的寬度和高度
@Override
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_content
measureWidth = (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_content
measureHeight = (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, 自己定義時最好也按照這個比例, 否則會顯得不和諧
5.這里是最重要的, 在onDraw方法里畫背景和圓球
@Override
protected 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);
}
到這里的時候, 就能看到畫好的背景和圓球了, 但卻是靜態(tài)的, 還不能動
6.定義枚舉變量, 用來記錄開關(guān)的狀態(tài)
private enum State {
OPEN, CLOSE
}
private State mCurrentState;
7.當(dāng)button被點(diǎn)擊時, 改變圓球的x坐標(biāo)和背景畫筆的顏色, 調(diào)用invalidate重繪界面
設(shè)置點(diǎn)擊事件
private void initData() {
...
setOnClickListener(this);
}
在 onClick方法里
@Override
public void onClick(View v) {
mCurrentState = (mCurrentState == State.CLOSE ? State.OPEN : State.CLOSE);
//綠色 #1AAC19
//灰色 #999999
if (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() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mSwitchBallx = ((float) animation.getAnimatedValue());
postInvalidate();
}
});
ValueAnimator color = ValueAnimator.ofObject(new ColorEvaluator(), startColor, endColor);
color.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
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() {
@Override
public void onAnimationStart(Animator animation) {
setClickable(false);
}
@Override
public void onAnimationEnd(Animator animation) {
setClickable(true);
}
});
animatorSet.start();
}
需要說明的是, 這里的難點(diǎn)在于如何讓圓球和x坐標(biāo)在指定時間內(nèi)圓滑地變換到另一個值, 以及如何讓顏色如何從灰色圓滑地變換到綠色。這里我使用的是值動畫(因?yàn)闀簳r沒有想到更好的方法)。坐標(biāo)值的變換比較簡單。顏色變化這里用到了估值器ArgbEvaluator
8.暴露接口獲取開關(guān)的狀態(tài)
這里我就不貼代碼了, 很簡單的
總的來說, 還是挺簡單的, 也就200多行代碼。參考demo: ATDragViewDemo
Paste_Image.png