github地址:LikeWeChatSwitchButton
首先我們來(lái)看一下微信中switchButton的效果, 就是下圖那個(gè)樣子, 打開(kāi)微信玩一下就知道了坑律。
慣例, 先上實(shí)現(xiàn)的效果
接下來(lái), 我就說(shuō)明如何一步步實(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();
}
}
在這里, 背景顏色和圓球顏色是從自定義屬性中取的纲刀, 如果沒(méi)有定義, 就取默認(rèn)的顏色蜈垮。
2.初始化一些東西雕什, 比如創(chuàng)建兩個(gè)畫(huà)筆
private void initData() {
mBallPaint = createPaint(switchViewBallColor, 0, Paint.Style.FILL, 0);
mBgPaint = createPaint(switchViewBgColor, 0, Paint.Style.FILL, 0);
...
}
3.在onSizeChanged方法里定義一些長(zhǎng)度和寬度
@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)有滑, 和用來(lái)畫(huà)圓角矩形的矩形, 特別注意這里的switchViewStrockWidth指的是如下圖這段
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, 自己定義時(shí)最好也按照這個(gè)比例嵌削, 否則會(huì)顯得不和諧
5.這里是最重要的毛好, 在onDraw方法里畫(huà)背景和圓球
@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);
}
到這里的時(shí)候望艺, 就能看到畫(huà)好的背景和圓球了, 但卻是靜態(tài)的肌访, 還不能動(dòng)
6.定義枚舉變量找默, 用來(lái)記錄開(kāi)關(guān)的狀態(tài)
private enum State {
OPEN, CLOSE
}
private State mCurrentState;
7.當(dāng)button被點(diǎn)擊時(shí), 改變圓球的x坐標(biāo)和背景畫(huà)筆的顏色吼驶, 調(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();
}
需要說(shuō)明的是惩激, 這里的難點(diǎn)在于如何讓圓球和x坐標(biāo)在指定時(shí)間內(nèi)圓滑地變換到另一個(gè)值, 以及如何讓顏色如何從灰色圓滑地變換到綠色旨剥。這里我使用的是值動(dòng)畫(huà)(因?yàn)闀簳r(shí)沒(méi)有想到更好的方法)咧欣。坐標(biāo)值的變換比較簡(jiǎn)單浅缸。顏色變化這里用到了估值器ArgbEvaluator
8.暴露接口獲取開(kāi)關(guān)的狀態(tài)
這里我就不貼代碼了轨帜, 很簡(jiǎn)單的