編輯:關於 Android 程式設計

今天要介紹的是一個會變形的按鈕。它可以矩形變圓形、圓形變矩形,也可以先變成進度條再變回圓形——整個過程是連續的屬性動畫,而不是換圖硬切。先看效果。

按鈕的外觀參數不少,全部開放成自訂屬性,這樣在 XML 裡就能直接調。
<resources>
<declare-styleable name="DynamicButton"></declare-styleable>
<declare-styleable name="ProgressButton"></declare-styleable>
</resources>
各屬性意義:
dybtn_color:按鈕正常狀態的背景色dybtn_corner_radius:圓角弧度dybtn_stroke_color:邊框顏色dybtn_stroke_width:邊框寬度dybtn_pressed_color:按下時的顏色pbtn_progresscolor:進度條按鈕的進度色pbtn_maxvalue:進度最大值pbtn_minvalue:進度最小值pbtn_progress:目前進度自訂屬性的解析一律在建構子中進行,實務上的標準做法是把解析邏輯抽成一個方法,讓所有建構子都呼叫它,避免重複。
public void initView(Context mContext, AttributeSet attrs, int defStyleAttr) {
TypedArray array = mContext.obtainStyledAttributes(
attrs, R.styleable.DynamicButton, defStyleAttr, 0);
mColor = array.getColor(R.styleable.DynamicButton_dybtn_color, DEFUALT_DYB_COLOR);
mPressedColor = array.getColor(R.styleable.DynamicButton_dybtn_pressed_color, DEFAULT_DYB_PRESSED_COLOR);
mCornerRadius = array.getDimensionPixelOffset(
R.styleable.DynamicButton_dybtn_corner_radius, dp2px(DEFUALT_DYB_CORNER_RADIUS));
mStrokeColor = array.getColor(R.styleable.DynamicButton_dybtn_stroke_color, DEFAULT_DYB_STROKE_COLOR);
mStrokeWidth = array.getDimensionPixelOffset(
R.styleable.DynamicButton_dybtn_stroke_width, dp2px(DEFAULT_DYB_STROKE_WIDTH));
mNormalDrawable = createDrawable(mColor, mCornerRadius, mStrokeWidth, mStrokeColor);
mPressedDrawable = createDrawable(mPressedColor, mCornerRadius, mStrokeWidth, mStrokeColor);
StateListDrawable listDrawable = new StateListDrawable();
listDrawable.addState(new int[]{android.R.attr.state_pressed}, mPressedDrawable);
listDrawable.addState(new int[]{android.R.attr.state_focused}, mPressedDrawable);
listDrawable.addState(new int[]{android.R.attr.state_selected}, mPressedDrawable);
listDrawable.addState(new int[]{}, mNormalDrawable);
setBackground(listDrawable);
array.recycle();
}
這裡值得多說一句的是 StateListDrawable。平常我們想讓控制項在按下與正常狀態有不同背景,都是寫一個 selector XML,而 selector 本質上就是透過這個類別實作的。用程式碼動態組裝的好處是顏色與圓角都能來自自訂屬性,不必再動態產生 XML。
public CustomGradientDrawable createDrawable(int mColor, float mCornerRadius,
int mStrokeWidth, int mStrokeColor) {
CustomGradientDrawable drawable = new CustomGradientDrawable();
drawable.setShape(GradientDrawable.RECTANGLE);
drawable.setStrokeColor(mStrokeColor);
drawable.setStrokeWidth(mStrokeWidth);
drawable.setColor(mColor);
drawable.setRadius(mCornerRadius);
return drawable;
}
注意這裡沒直接用 GradientDrawable,而是自訂了一個子類。看起來只是多包一層、有些屬性還跟父類重複,為什麼要多此一舉?
因為要用屬性動畫。屬性動畫有一個硬性前提:目標屬性必須有對應的 getter 與 setter。要讓 color 能漸變,就得有 setColor 與 getColor;要讓圓角能漸變,就得有 setRadius 與 getRadius。自訂子類就是為了把這些 setter/getter 補齊,讓 ObjectAnimator 有東西可以操作。
要變形,就得描述「變成什麼樣子」,而目標狀態牽涉到寬、高、圓角、邊框寬、邊框色、背景色等七八個參數。這種場合正適合用 Builder 模式收斂成鏈式呼叫。
/** 用 Builder 模式描述「目標形狀」 */
public static class PropertyParam {
public int mHeight;
public int mWidth;
public int mColor;
public int mPressedColor;
public float mCornerRadius;
public int mStrokeWidth;
public int mStrokeColor;
public long duration;
public String text;
public Drawable icon;
public static PropertyParam build() { return new PropertyParam(); }
public PropertyParam setHeight(int v) { this.mHeight = v; return this; }
public PropertyParam setWidth(int v) { this.mWidth = v; return this; }
public PropertyParam setColor(int v) { this.mColor = v; return this; }
public PropertyParam setCornerRadius(int v) { this.mCornerRadius = v; return this; }
public PropertyParam setStrokeWidth(int v) { this.mStrokeWidth = v; return this; }
public PropertyParam setStrokeColor(int v) { this.mStrokeColor = v; return this; }
public PropertyParam setPressedColor(int v) { this.mPressedColor = v; return this; }
public PropertyParam duration(long v) { this.duration = v; return this; }
public PropertyParam text(String v) { this.text = v; return this; }
public PropertyParam icon(Drawable v) { this.icon = v; return this; }
}
沒接觸過 Builder 模式的話可以先查一下,這裡不展開。重點是:鏈式呼叫讓「描述一個形狀」這件事變得像填表單一樣直觀。
PropertyParam 只描述目標。動畫需要起點與終點,所以還要一個結構把兩邊並存。按鈕目前的形狀參數很容易從自身讀出來,把它和目標參數組裝起來,就是 AnimatorParams。
public static class AnimatorParams {
private float fromCornerRadius, toCornerRadius;
private int fromHeight, toHeight;
private int fromWidth, toWidth;
private int fromColor, toColor;
private int fromStrokeWidth, toStrokeWidth;
private int fromStrokeColor, toStrokeColor;
private long duration;
private DynamicButton mButton;
private AnimatorBuilder.AnimatorListener mListener;
public AnimatorParams(DynamicButton mButton) { this.mButton = mButton; }
public static AnimatorParams build(DynamicButton b) { return new AnimatorParams(b); }
public AnimatorParams height(int from, int to) { this.fromHeight = from; this.toHeight = to; return this; }
public AnimatorParams width(int from, int to) { this.fromWidth = from; this.toWidth = to; return this; }
public AnimatorParams cornerRadius(float from, float to){ this.fromCornerRadius = from; this.toCornerRadius = to; return this; }
public AnimatorParams strokeWidth(int from, int to) { this.fromStrokeWidth = from; this.toStrokeWidth = to; return this; }
public AnimatorParams strokeColor(int from, int to) { this.fromStrokeColor = from; this.toStrokeColor = to; return this; }
public AnimatorParams color(int from, int to) { this.fromColor = from; this.toColor = to; return this; }
public AnimatorParams duration(long d) { this.duration = d; return this; }
public AnimatorParams listener(AnimatorListener l) { this.mListener = l; return this; }
}
有了起點與終點,熟悉屬性動畫的人應該已經知道怎麼寫了。這裡有兩個技術細節:
一是寬高屬於 View 的版面參數,不是 Drawable 的屬性,所以要用 ValueAnimator 搭配 addUpdateListener,在每一幀把值寫回 LayoutParams。二是顏色漸變不能靠單純的整數插值(那會在中間出現一堆髒色),必須掛上 ArgbEvaluator,讓插值走 ARGB 色彩空間。
public static void startAnimator(final AnimatorParams params) {
ValueAnimator heightAnimator = ValueAnimator.ofInt(params.fromHeight, params.toHeight);
heightAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
ViewGroup.LayoutParams lp = params.mButton.getLayoutParams();
lp.height = (Integer) animation.getAnimatedValue();
params.mButton.setLayoutParams(lp);
}
});
ValueAnimator widthAnimator = ValueAnimator.ofInt(params.fromWidth, params.toWidth);
widthAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
ViewGroup.LayoutParams lp = params.mButton.getLayoutParams();
lp.width = (Integer) animation.getAnimatedValue();
params.mButton.setLayoutParams(lp);
}
});
CustomGradientDrawable drawable =
(CustomGradientDrawable) params.mButton.getNormalDrawable();
ObjectAnimator radiusAnimator = ObjectAnimator.ofFloat(
drawable, "radius", params.fromCornerRadius, params.toCornerRadius);
ObjectAnimator strokeWidthAnimator = ObjectAnimator.ofInt(
drawable, "strokeWidth", params.fromStrokeWidth, params.toStrokeWidth);
ObjectAnimator strokeColorAnimator = ObjectAnimator.ofInt(
drawable, "strokeColor", params.fromStrokeColor, params.toStrokeColor);
ObjectAnimator colorAnimator = ObjectAnimator.ofInt(
drawable, "color", params.fromColor, params.toColor);
colorAnimator.setEvaluator(new ArgbEvaluator()); // 顏色必須用 ARGB 評估器
AnimatorSet animators = new AnimatorSet();
animators.setDuration(params.duration);
animators.play(radiusAnimator)
.with(strokeColorAnimator)
.with(strokeWidthAnimator)
.with(widthAnimator)
.with(heightAnimator)
.with(colorAnimator);
animators.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
params.mListener.onAnimatorEnd();
}
});
animators.start();
}
這個可變形按鈕的核心概念其實只有三句話:
第一,把外觀狀態完整描述成數據(PropertyParam 存目標、AnimatorParams 存起點與終點)。
第二,為了讓數據能被動畫驅動,必須自訂 Drawable 子類把 setter/getter 補齊,這是屬性動畫的入場券。
第三,用 AnimatorSet 把寬、高、圓角、邊框、顏色這幾條動畫併發播放,時間軸一致,視覺上才會是「同一個物體在變形」而不是「多個屬性各自亂跳」。
至於「矩形 → 進度條 → 圓形」這種連續變形,本質上就是連續呼叫兩次 startAnimator:第二次的 from 值取自第一次的 to 值。理解了這一點,後面的 ProgressButton 就不難補上。由於完整程式碼量偏大,這裡只把最關鍵的思路與程式碼呈現出來,其餘部分請對照原始碼閱讀。
用反射呼叫系統隱藏遠程服務,實作來電攔截
早期版本的 Android 在 TelephonyManager 上開放了一個 endCall() 方法,掛斷來電一行程式碼就能搞定。但 Google 後來意識到,對一支
Android 列表互動實戰:PullToRefresh 實現下拉刷新與左滑刪除
寫在前面:ListView 的下拉刷新功能,做 Android 的同學大概都不陌生。如今 Google 官方的 SwipeRefreshLayout 效果在很多 App
Android 中利用 shape 定義控件外觀的用法
在 Android 中,我們常透過 shape 來定義控件的外觀屬性。以下整理了 shape 的幾個常用標籤與屬性。 先看下面的程式碼: <shape> &
自定義 ClearEditText:為輸入框加上一鍵清空按鈕
公司產品陸續在升級,這輪任務是優化程式碼結構與專案架構,於是開始全專案找冗餘。 先說需求場景。基本上每個 App 都有登入頁,登入頁少不了輸入框。當使用者發現內容打錯或想