編輯:關於 Android 程式設計
昨天偶然看到 UI 給的一個交互效果,原圖如下:

於是大致模仿了一下下面的 login button。這裡沒有實現全部效果,感興趣的同學可以自行完善後面的展開動畫。
這個 View 涉及的知識點並不難:
View 的坐標系知識;Canvas 的基本 API(畫矩形、畫扇形等);自定義屬性(在 attr 中提供選項);屬性動畫(ObjectAnimator 和 ValueAnimator)。
下面我們一步步實現這個按鈕。
先寫一個自定義類繼承 View,在構造函數中獲取自定義屬性的值:
public ATLoginButton(Context context) { this(context, null); } public ATLoginButton(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ATLoginButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ATLoginButton, defStyleAttr, R.style.def_button_style); int indexCount = typedArray.getIndexCount(); for (int i = 0; i < indexCount; i++) { int attr = typedArray.getIndex(i); switch (attr) { case R.styleable.ATLoginButton_button_color: buttonColor = typedArray.getColor(attr, getResources().getColor(R.color.colorAccent)); break; case R.styleable.ATLoginButton_text_color: textColor = typedArray.getColor(attr, getResources().getColor(R.color.colorW)); break; case R.styleable.ATLoginButton_text_size: textSize = typedArray.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, getResources().getDisplayMetrics())); break; case R.styleable.ATLoginButton_login_text: loginDesc = typedArray.getString(attr); break; case R.styleable.ATLoginButton_failed_text: failDesc = typedArray.getString(attr); break; case R.styleable.ATLoginButton_circle_loading_color: circlerLoadingColor = typedArray.getColor(attr, Color.GRAY); break; case R.styleable.ATLoginButton_circle_loading_width: circleLoadingLineWidth = typedArray.getDimensionPixelOffset(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics())); break; case R.styleable.ATLoginButton_failed_button_color: failedButtonColor = typedArray.getColor(attr, Color.GRAY); break; } } typedArray.recycle(); init(); }
重寫 onMeasure,確定並測量 View 的大小和測量模式:
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); // 主要view支持wrap_content屬性 int widthSize; int heightSize; if (widthMode == MeasureSpec.AT_MOST || widthMode == MeasureSpec.UNSPECIFIED) { widthSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DE_W, getResources().getDisplayMetrics()); widthMeasureSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY); } if (heightMode == MeasureSpec.AT_MOST || heightMode == MeasureSpec.UNSPECIFIED) { heightSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DE_H, getResources().getDisplayMetrics()); heightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY); } super.onMeasure(widthMeasureSpec, heightMeasureSpec); }
獲取測量後的寬高:
@Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mWidth = w; mHeight = h; circleAndRoundSize = h / 2; textPoint = getTextPointInView(loginDesc); buttonRectF = new RectF(0, 0, mWidth, mHeight); mText = loginDesc; viewState = LoginViewState.NORMAL_STATE; }
最後一步是 onDraw——此時我們已經完成約 80% 的工作,剩下的就是把內容畫到畫布上並讓它動起來。
畫圓角 button,注意動起來時兩個半圓要合併成一個完整的圓,所以倒角半徑就是 View 高度的一半:
private void drawButton(Canvas canvas) { canvas.drawRoundRect(buttonRectF, circleAndRoundSize, circleAndRoundSize, buttonPaint); }
畫 button 上的文字:
private void drawTextDesc(Canvas canvas, String textDesc) { canvas.drawText(textDesc, textPoint.x, textPoint.y, textPaint); }
為了讓文字居中,需要獲取文字測量後的信息:
private Point getTextPointInView(String textDesc) { Point point = new Point(); int textW = (mWidth - (int) textPaint.measureText(textDesc)) / 2; Paint.FontMetrics fm = textPaint.getFontMetrics(); int textH = (int) Math.ceil(fm.descent - fm.top); point.set(textW, (mHeight + textH) / 2); return point; }
畫扇形(即 loading 的圓圈):
private void drawCircleLoading(Canvas canvas) { float circleSpacing = circleAndRoundSize / 4; float x = (mHeight - 10) / 2; float y = (mHeight - 10) / 2; canvas.translate(mWidth / 2, y); canvas.scale(1F, 1F); canvas.rotate(0); RectF rectF = new RectF(-x + circleSpacing, -y + circleSpacing, x - circleSpacing, y - circleSpacing); canvas.drawArc(rectF, -45, 270, false, circleLoadingPaint); }
所有圖形元素準備就緒後,再提供幾個方法:開始登錄(button 變圓形)、登錄結果(成功/失敗都變回 button),以及變圓時的旋轉動畫。
public void buttonLoginAction() { setClickable(false); buttonPaint.setColor(buttonColor); if (viewState != LoginViewState.NORMAL_STATE) { circleLoadingPaint.setColor(circlerLoadingColor); } ValueAnimator valueAnimator = getValA(0F, 1F); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { Float aFloat = Float.valueOf(valueAnimator.getAnimatedValue().toString()); int left = (int) ((aFloat) * mWidth); int jL = mWidth / 2 - circleAndRoundSize; if (left >= jL) { buttonRectF = new RectF(jL, 0, jL + mHeight, mHeight); textPaint.setColor(Color.TRANSPARENT); isLoading = true; invalidate(); valueAnimator.cancel(); startLoading(); viewState = LoginViewState.LOADING_STATE; return; } float right = (1 - aFloat) * mWidth; buttonRectF = new RectF(left, 0, right, mHeight); invalidate(); } }); valueAnimator.start(); }
圓圈變回 button 的方法:
public void buttonLoaginResultAciton(final boolean isSuccess) { viewState = isSuccess ? LoginViewState.SUCCESS_STATE : LoginViewState.FAILED_STATE; stopLoading(); ValueAnimator valueAnimator = getValA(0F, 1F); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { int jL = mWidth / 2 - circleAndRoundSize; Float aFloat = Float.valueOf(valueAnimator.getAnimatedValue().toString()); int left = (int) ((1 - aFloat) * jL); float right = jL + mHeight + jL * aFloat; buttonRectF = new RectF(left, 0, right, mHeight); textPaint.setColor(textColor); if (isSuccess){ mText = loginDesc; textPoint = getTextPointInView(mText); buttonPaint.setColor(buttonColor); invalidate(); if (aFloat.intValue() == 1) { setClickable(true); buttonRectF = new RectF(0, 0, mWidth, mHeight); invalidate(); valueAnimator.cancel(); } }else { mText = failDesc; textPoint = getTextPointInView(mText); buttonPaint.setColor(failedButtonColor); invalidate(); if (aFloat.intValue() == 1) { setClickable(true); buttonRectF = new RectF(0, 0, mWidth, mHeight); invalidate(); shakeFailed(); valueAnimator.cancel(); } } } }); valueAnimator.start(); }
最後在 MainActivity 裡使用:
private void addListener2Button(final ATLoginButton atLoginButton, final boolean loaginStatus) { atLoginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { atLoginButton.buttonLoginAction(); atLoginButton.postDelayed(new Runnable() { @Override public void run() { atLoginButton.buttonLoaginResultAciton(loaginStatus); String notice = loaginStatus ? "登陸成功,重置button狀態" : "登錄失敗,顯示失敗狀態"; Toast.makeText(getApplicationContext(), notice, Toast.LENGTH_SHORT).show(); } }, 3000); } }); }
由於這個 demo 只有一個自定義 View,項目就不單獨上傳了,下面附上完整代碼,感興趣的同學可以放進 Android Studio 跑一下。
public class ATLoginButton extends View { private static final float DE_W = 280.F; private static final float DE_H = 65.F; private static final long ANIMATION_TIME = 800; private int buttonColor; private int textColor; private int textSize; private int circlerLoadingColor; private int failedButtonColor; private int circleLoadingLineWidth; private String loginDesc; private String failDesc; private String mText; private Paint buttonPaint; private Paint textPaint; private Paint circleLoadingPaint; private int mHeight; private int mWidth; private int circleAndRoundSize; private RectF buttonRectF; private Point textPoint; private boolean isLoading; private RotateAnimation rotateAnimation; private int viewState; public ATLoginButton(Context context) { this(context, null); } public ATLoginButton(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ATLoginButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ATLoginButton, defStyleAttr, R.style.def_button_style); int indexCount = typedArray.getIndexCount(); for (int i = 0; i < indexCount; i++) { int attr = typedArray.getIndex(i); switch (attr) { case R.styleable.ATLoginButton_button_color: buttonColor = typedArray.getColor(attr, getResources().getColor(R.color.colorAccent)); break; case R.styleable.ATLoginButton_text_color: textColor = typedArray.getColor(attr, getResources().getColor(R.color.colorW)); break; case R.styleable.ATLoginButton_text_size: textSize = typedArray.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, getResources().getDisplayMetrics())); break; case R.styleable.ATLoginButton_login_text: loginDesc = typedArray.getString(attr); break; case R.styleable.ATLoginButton_failed_text: failDesc = typedArray.getString(attr); break; case R.styleable.ATLoginButton_circle_loading_color: circlerLoadingColor = typedArray.getColor(attr, Color.GRAY); break; case R.styleable.ATLoginButton_circle_loading_width: circleLoadingLineWidth = typedArray.getDimensionPixelOffset(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics())); break; case R.styleable.ATLoginButton_failed_button_color: failedButtonColor = typedArray.getColor(attr, Color.GRAY); break; } } typedArray.recycle(); init(); } private void init() { buttonPaint = creatPaint(buttonColor, 0, Paint.Style.FILL, circleLoadingLineWidth); circleLoadingPaint = creatPaint(circlerLoadingColor, 0, Paint.Style.STROKE, circleLoadingLineWidth); textPaint = creatPaint(textColor, textSize, Paint.Style.FILL, circleLoadingLineWidth); } private Paint creatPaint(int paintColor, int textSize, Paint.Style style, int lineWidth) { Paint paint = new Paint(); paint.setColor(paintColor); paint.setAntiAlias(true); paint.setStrokeWidth(lineWidth); paint.setDither(true); paint.setTextSize(textSize); paint.setStyle(style); paint.setStrokeCap(Paint.Cap.ROUND); paint.setStrokeJoin(Paint.Join.ROUND); return paint; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int widthSize; int heightSize; if (widthMode == MeasureSpec.AT_MOST || widthMode == MeasureSpec.UNSPECIFIED) { widthSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DE_W, getResources().getDisplayMetrics()); widthMeasureSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY); } if (heightMode == MeasureSpec.AT_MOST || heightMode == MeasureSpec.UNSPECIFIED) { heightSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DE_H, getResources().getDisplayMetrics()); heightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY); } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mWidth = w; mHeight = h; circleAndRoundSize = h / 2; textPoint = getTextPointInView(loginDesc); buttonRectF = new RectF(0, 0, mWidth, mHeight); mText = loginDesc; viewState = LoginViewState.NORMAL_STATE; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); drawButton(canvas); drawTextDesc(canvas, mText); if (isLoading) { drawCircleLoading(canvas); } } private void drawCircleLoading(Canvas canvas) { float circleSpacing = circleAndRoundSize / 4; float x = (mHeight - 10) / 2; float y = (mHeight - 10) / 2; canvas.translate(mWidth / 2, y); canvas.scale(1F, 1F); canvas.rotate(0); RectF rectF = new RectF(-x + circleSpacing, -y + circleSpacing, x - circleSpacing, y - circleSpacing); canvas.drawArc(rectF, -45, 270, false, circleLoadingPaint); } private void drawTextDesc(Canvas canvas, String textDesc) { canvas.drawText(textDesc, textPoint.x, textPoint.y, textPaint); } private void drawButton(Canvas canvas) { canvas.drawRoundRect(buttonRectF, circleAndRoundSize, circleAndRoundSize, buttonPaint); } private Point getTextPointInView(String textDesc) { Point point = new Point(); int textW = (mWidth - (int) textPaint.measureText(textDesc)) / 2; Paint.FontMetrics fm = textPaint.getFontMetrics(); int textH = (int) Math.ceil(fm.descent - fm.top); point.set(textW, (mHeight + textH) / 2); return point; } public void buttonLoginAction() { setClickable(false); buttonPaint.setColor(buttonColor); if (viewState != LoginViewState.NORMAL_STATE) { circleLoadingPaint.setColor(circlerLoadingColor); } ValueAnimator valueAnimator = getValA(0F, 1F); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { Float aFloat = Float.valueOf(valueAnimator.getAnimatedValue().toString()); int left = (int) ((aFloat) * mWidth); int jL = mWidth / 2 - circleAndRoundSize; if (left >= jL) { buttonRectF = new RectF(jL, 0, jL + mHeight, mHeight); textPaint.setColor(Color.TRANSPARENT); isLoading = true; invalidate(); valueAnimator.cancel(); startLoading(); viewState = LoginViewState.LOADING_STATE; return; } float right = (1 - aFloat) * mWidth; buttonRectF = new RectF(left, 0, right, mHeight); invalidate(); } }); valueAnimator.start(); } public void buttonLoaginResultAciton(final boolean isSuccess) { viewState = isSuccess ? LoginViewState.SUCCESS_STATE : LoginViewState.FAILED_STATE; stopLoading(); ValueAnimator valueAnimator = getValA(0F, 1F); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { int jL = mWidth / 2 - circleAndRoundSize; Float aFloat = Float.valueOf(valueAnimator.getAnimatedValue().toString()); int left = (int) ((1 - aFloat) * jL); float right = jL + mHeight + jL * aFloat; buttonRectF = new RectF(left, 0, right, mHeight); textPaint.setColor(textColor); if (isSuccess){ mText = loginDesc; textPoint = getTextPointInView(mText); buttonPaint.setColor(buttonColor); invalidate(); if (aFloat.intValue() == 1) { setClickable(true); buttonRectF = new RectF(0, 0, mWidth, mHeight); invalidate(); valueAnimator.cancel(); } }else { mText = failDesc; textPoint = getTextPointInView(mText); buttonPaint.setColor(failedButtonColor); invalidate(); if (aFloat.intValue() == 1) { setClickable(true); buttonRectF = new RectF(0, 0, mWidth, mHeight); invalidate(); shakeFailed(); valueAnimator.cancel(); } } } }); valueAnimator.start(); } private void stopLoading() { isLoading = false; circleLoadingPaint.setColor(Color.TRANSPARENT); if (null != rotateAnimation) { rotateAnimation.cancel(); } } private void shakeFailed() { ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(this, "translationX", 0, 10); objectAnimator.setDuration(500); objectAnimator.setInterpolator(new CycleInterpolator(10)); objectAnimator.start(); } private void startLoading() { rotateAnimation = new RotateAnimation(0F, 360F, mWidth / 2, mHeight / 2); rotateAnimation.setDuration(500); rotateAnimation.setRepeatCount(Animation.INFINITE); rotateAnimation.setInterpolator(new LinearInterpolator()); startAnimation(rotateAnimation); } private static class LoginViewState { static final int NORMAL_STATE = 90; static final int LOADING_STATE = 91; static final int FAILED_STATE = 92; static final int SUCCESS_STATE = 93; } }
Android 組件化開發(2):用 GridView 實作網格布局的 RadioButton 矩陣
前言 一般我們用 RadioGroup 包住一批 RadioButton,就能拿到「單選互斥」的效果,省心省力。問題是 RadioGroup 骨子裡只是一個耿直的 Lin
Fragment 全解析:生命週期、加載與通信機制
1.概述 Fragment 是 Activity 中用戶界面的一部分行為或組成單元,主要用於支持在大屏幕上動態、更靈活地組合或交換 UI 組件。通過將 Activity
Android 藍牙源碼分析:Inquiry Result 之後上層做了什麼
前一篇我們追了底層如何解析藍牙晶片回報的搜尋結果,這篇接著往下走:這些裝置資訊往上一層傳之後,framework 與 Settings 應用是怎麼把它變成螢幕上那一列列可
Android 中使用 Pull 解析 XML 數據的完整示例
Pull 解析 XML 的方式與 SAX 大致相同,兩者都是基於事件驅動的。使用 Pull 解析 XML 通常需要以下幾個步驟: 1)通過 XMLPullParserFa