編輯:關於 Android 程式設計
版本 1.0,2014.5.17 起筆、2014.6.1 補完。版權 © 2014 kince,轉載請註明出處。
要自己寫一個滑動開關,先回頭看系統是怎麼做的會省很多力氣。
@RemoteView
public class Button extends TextView {
public Button(Context context) { this(context, null); }
public Button(Context context, AttributeSet attrs) {
this(context, attrs, com.android.internal.R.attr.buttonStyle);
}
public Button(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
...
}
Button 直接繼承 TextView,差別只在建構子中帶入了 buttonStyle 樣式,並自行處理無障礙相關的初始化。但並非所有子類都這麼輕薄。
Button 的直接子類只有一個抽象類 CompoundButton,而 CheckBox、RadioButton、Switch、ToggleButton 四者都實作自它。因此 CompoundButton 才是重點。
建構子中讀取兩個屬性:一個 Drawable 用於設置「按鈕圖」,一個 boolean 表示是否已勾選。
public CompoundButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs,
com.android.internal.R.styleable.CompoundButton, defStyle, 0);
Drawable d = a.getDrawable(com.android.internal.R.styleable.CompoundButton_button);
if (d != null) { setButtonDrawable(d); }
boolean checked = a.getBoolean(com.android.internal.R.styleable.CompoundButton_checked, false);
setChecked(checked);
a.recycle();
}
setButtonDrawable 寫得很值得學習。它先判斷傳入的 Drawable 是否為空,若不為空且原本已有 Drawable,就先取消舊 Drawable 的 callback 並呼叫 unscheduleDrawable 把它從 Choreographer 的動畫佇列中摘除,再設定新的 callback、可見性與最小高度,最後呼叫 refreshDrawableState() 更新狀態。換 Drawable 時主動清理舊物件,是避免記憶體與 callbacks 殘留的標準做法。
setChecked 裡藏著一個巧妙手法:
public void setChecked(boolean checked) {
if (mChecked != checked) {
mChecked = checked;
refreshDrawableState();
notifyViewAccessibilityStateChangedIfNeeded(...);
// 避免 listener 中再呼叫 setChecked 造成無限遞迴
if (mBroadcasting) { return; }
mBroadcasting = true;
if (mOnCheckedChangeListener != null) {
mOnCheckedChangeListener.onCheckedChanged(this, mChecked);
}
if (mOnCheckedChangeWidgetListener != null) {
mOnCheckedChangeWidgetListener.onCheckedChanged(this, mChecked);
}
mBroadcasting = false;
}
}
一個 mBroadcasting 旗標就擋掉了「在 listener 回呼裡改狀態」導致的無限遞迴,這個模式在 Android 原始碼中到處可見,值得直接借用。
onDraw 的重點是算出四邊座標:依垂直方向的 gravity 決定 top(靠下、居中或預設),bottom 由 top 加上圖片高度得出,left/right 則視 isLayoutRtl() 判斷是否要鏡像,最後 setBounds 後畫上去。
CheckBox 幾乎就是 Button 的翻版,只是換用自己的 checkboxStyle。RadioButton additionally 覆寫了 toggle(),避免已勾選時又被切回:
@Override
public void toggle() {
// 已勾選的 radio button 不允許再切換(與 checkbox 不同)
if (!isChecked()) {
super.toggle();
}
}
ToggleButton 的實作同樣單純,Switch 稍複雜一些,有興趣可自行追。這也說明一件事:換湯不換藥的差異都靠覆寫少數幾個方法解決,共用邏輯全在 CompoundButton。
圖 1-1
圖 1-2
原理很單純:一張背景圖畫著「開/關」兩段文字,上面蓋一顆圓鈕;圓鈕左右滑動時遮住其中一側,於是任一時刻只看得見一個狀態。
實作上就是先畫背景,再在其上計算並畫出圓鈕位置,滑動時只需要更新圓鈕的 X 座標。
滑塊圖:
背景圖(開/關兩款):
自訂控制項可以繼承 Button、繼承 Button 的子類,也可以直接繼承 View。滑動開關就是「左右滑動改變顯示內容」這麼一件事,不需要 Button 的剩餘能力;若繼承系統控制項,反而會帶進一堆用不到的機制。因此直接繼承 View 最合適。
實作步驟:
public class SlideButton extends View {
private Bitmap slideBitMap; // 滑塊圖
private Bitmap switchBitMap; // 背景圖
private int slideBitMapWidth;
private int switchBitMapWidth;
private int switchBitMapHeight;
private boolean currentState; // 開關狀態
private boolean isSliding = false; // 是否正在滑動中
private int currentX; // 目前滑塊位置
private OnToggleStateChangedListener mChangedListener; // 回呼介面
public SlideButton(Context context) { this(context, null); }
public SlideButton(Context context, AttributeSet attrs) { this(context, attrs, 0); }
public SlideButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initBitmap();
}
private void initBitmap() {
slideBitMap = BitmapFactory.decodeResource(getResources(), R.drawable.slide_button_background);
switchBitMap = BitmapFactory.decodeResource(getResources(), R.drawable.switch_background);
slideBitMapWidth = slideBitMap.getWidth();
switchBitMapWidth = switchBitMap.getWidth();
switchBitMapHeight = switchBitMap.getHeight();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// 控制項尺寸直接取背景圖尺寸
setMeasuredDimension(switchBitMapWidth, switchBitMapHeight);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(switchBitMap, 0, 0, null);
if (isSliding) {
// 滑動中:依目前 X 座標即時計算,並夾在合法範圍內
int dis = currentX - slideBitMapWidth / 2;
if (dis < 0) dis = 0;
else if (dis > switchBitMapWidth - slideBitMapWidth) {
dis = switchBitMapWidth - slideBitMapWidth;
}
canvas.drawBitmap(slideBitMap, dis, 0, null);
} else {
// 靜止:依狀態畫在最左或最右
if (currentState) {
canvas.drawBitmap(slideBitMap, switchBitMapWidth - slideBitMapWidth, 0, null);
} else {
canvas.drawBitmap(slideBitMap, 0, 0, null);
}
}
super.onDraw(canvas);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
isSliding = true;
currentX = (int) event.getX();
break;
case MotionEvent.ACTION_MOVE:
currentX = (int) event.getX();
break;
case MotionEvent.ACTION_UP:
isSliding = false;
// 以背景中線判斷最終狀態
boolean state = currentX > switchBitMapWidth / 2;
if (state != currentState && mChangedListener != null) {
mChangedListener.onToggleStateChanged(state);
}
currentState = state;
break;
}
invalidate();
return true;
}
public boolean isToggleState() { return currentState; }
public void setToggleState(boolean currentState) { this.currentState = currentState; }
public void setmChangedListener(OnToggleStateChangedListener l) { this.mChangedListener = l; }
}
回呼介面:
public interface OnToggleStateChangedListener {
void onToggleStateChanged(boolean state);
}
使用端在 Fragment 中註冊監聽並做 Toast 提示:
slidebutton = (SlideButton) rootView.findViewById(R.id.slidebutton1);
slidebutton.setToggleState(true); // 設定初始為開
slidebutton.setmChangedListener(this);
@Override
public void onToggleStateChanged(boolean state) {
FragmentActivity activity = getActivity();
Toast.makeText(activity, state ? "開關打開" : "開關關閉", 0).show();
}
後續可優化的方向還不少:改用自訂屬性在 XML 中指定素材、加入滑動動畫曲線、支援點擊直接切換、以及處理控制項禁用狀態。未完待續。
Android 應用架構搭建實錄:從 MVC 走向 MVP 的分層設計
一、前言:為什麼要重新搭一次框架 Android 團隊普遍規模不大,架構的重要性在很多公司並不明顯;加上開源框架層出不窮,上手一個專案的成本被壓得很低。但這不代表架構不重
動手實現 bilibili 風格彈幕效果
自從 bilibili 把彈幕玩火之後,邊看視頻邊看吐槽已經成了很多人的日常。那我們能不能自己也實現一套類似的彈幕功能呢?答案是肯定的。動手之前,先理清思路:一套彈幕系統
自定義 ViewGroup 實現流式佈局(FlowLayout)
流式佈局的規則很直觀:每一行的高度取本行中最高元素的高度;當一個元素在本行放不下時,直接換到下一行。 效果如下: 實現思路 自定義 ViewGroup 只需要做兩件
Android 動畫實戰:復刻樂動力旋轉動畫
一、前言 在 App 泛濫的市場上,各家功能抄來抄去,想做出精品,沒有自己的風格、沒有讓用戶眼前一亮的效果,很難留住人——隨時都會被下一個替代品頂掉。「簡約而不簡單」「用