編輯:關於 Android 程式設計
Flux 不是框架,而是一套處理 UI 狀態的思路。正因為它只是一套約定,所以在 Android 上採用時不需要引入任何新的程式庫,你只要理解並遵循這套模式。
Flux 由 Facebook 提出,用於建構其客戶端 Web 應用。它與 Clean Architecture 一樣並非為行動裝置設計,但特性簡單,移植到 Android 專案相當容易。
它最大的特點是單向資料流,UI 狀態的更新模式則承襲 MVC 的設計思想。Android Flux 同樣不是具體框架,你要做的是理解這套思想、遵循這種開發模式,然後寫自己的程式碼。

一、資料流永遠是單向的。這是 Flux 架構的核心,也是它簡單易學的原因,同時讓測試變得容易。
二、應用被切成三個主要部分:
這三者透過 Action 溝通——Action 是一個簡單的物件,以 type 區別種類,並攜帶與操作相關的資料。
在 Android 上使用 Flux,目的是在簡單性、可擴充性與可測試性之間取得平衡。第一步是把 Flux 元素對應到 Android 的元件:
View → Activity 或 FragmentDispatcher → 一個事件總線(event bus),範例使用 Otto,其他實作亦可Action 的實作和 POJO 一樣簡單,兩個主要屬性:Type(一個字串,定義事件類型)與 Data(一個 Map,裝載本次操作的資料)。
Store 回應 Dispatcher 送來的 Action,執行業務邏輯,然後送出 change 事件。Store 唯一的輸出就是這個事件;其他對其內部狀態有興趣的元件必須監聽該事件,再向 Store 查詢所需資料。因此 Store 必須對外公開一個取得應用狀態的介面,讓 View 能查詢並據以更新 UI。
界面上有一個 Button 與一個 TextView,點擊 Button 後讓 TextView 顯示文字。常規做法是把邏輯寫在 Activity 裡,MVP 則放在 Presenter 層。在 Flux 架構下:View 產生 Action → Dispatcher 調度 → Store 處理 → 資料顯示出來。
public class Action {
private final String type;
private final HashMap<String, Object> data;
public Action(String type, HashMap<String, Object> data) {
this.type = type;
this.data = data;
}
public static Builder type(String type) {
return new Builder().with(type);
}
public String getType() {
return type;
}
public HashMap getData() {
return data;
}
public static class Builder {
private String type;
private HashMap<String, Object> data;
Builder with(String type) {
if (type == null) {
throw new IllegalArgumentException("Type may not be null.");
}
this.type = type;
this.data = new HashMap<>();
return this;
}
public Builder bundle(String key, Object value) {
if (key == null) {
throw new IllegalArgumentException("Key may not be null.");
}
if (value == null) {
throw new IllegalArgumentException("Value may not be null.");
}
data.put(key, value);
return this;
}
public Action build() {
if (TextUtils.isEmpty(type)) {
throw new IllegalArgumentException("At least one key is required.");
}
return new Action(type, data);
}
}
}
每個 Action 有兩個屬性:一個標記 Type,另一個用 Map 存放傳送的資料。Builder 模式讓建立過程可讀性更好,也順帶做了 null 檢查。
public interface ShowActions {
String TODO_SHOW = "todo-show";
String GET_TEXT = "get-text";
}
定義一個類別,針對各種 View 事件產生對應的 Action。注意這裡不是直接 new Action,而是交給調度器分發:
public class ActionsCreator {
private static ActionsCreator instance;
final Dispatcher mDispatcher;
ActionsCreator(Dispatcher dispatcher) {
mDispatcher = dispatcher;
}
public static ActionsCreator get(Dispatcher dispatcher) {
if (instance == null) {
instance = new ActionsCreator(dispatcher);
}
return instance;
}
public void create(String text) {
mDispatcher.dispatch(ShowActions.TODO_SHOW, ShowActions.GET_TEXT, text);
}
}
事件分發使用 Otto 的 Bus:
public class Dispatcher {
private final Bus bus;
private static Dispatcher instance;
Dispatcher(Bus bus) {
this.bus = bus;
}
public static Dispatcher get(Bus bus) {
if (instance == null) {
instance = new Dispatcher(bus);
}
return instance;
}
public void register(final Object cls) {
bus.register(cls);
}
public void unRegister(final Object cls) {
bus.unregister(cls);
}
public void emitChange(Store.StoreChangeEvent o) {
post(o);
}
public void dispatch(String type, Object... data) {
if (TextUtils.isEmpty(type)) {
throw new IllegalArgumentException("Type must not be empty");
}
if (data.length % 2 != 0) {
throw new IllegalArgumentException("Data must be a valid list of key");
}
Action.Builder actionBuilder = Action.type(type);
for (int i = 0; i < data.length; i++) {
String key = (String) data[i++];
Object value = data[i++];
actionBuilder.bundle(key, value);
}
post(actionBuilder.build());
}
private void post(final Object event) {
bus.post(event);
}
}
dispatch 把傳入的 key-value 序列解析成 Action 再發出去。此時訂閱了該 Action 的 Store 就會接手處理。
public abstract class Store {
final Dispatcher mDispatcher;
protected Store(Dispatcher dispatcher) {
this.mDispatcher = dispatcher;
}
void emitStoreChange() {
mDispatcher.emitChange(changeEvent());
}
abstract StoreChangeEvent changeEvent();
public abstract void onAction(Action action);
public interface StoreChangeEvent { }
}
onAction 負責判斷與分發 Action,StoreChangeEvent 則作為狀態變化的載體,可自行實作並在其中加入攜帶資料的欄位。
public class ShowStore extends Store {
private static ShowStore instance;
private String showText;
public ShowStore(Dispatcher dispatcher) {
super(dispatcher);
}
public static ShowStore get(Dispatcher dispatcher) {
if (instance == null) {
instance = new ShowStore(dispatcher);
}
return instance;
}
@Subscribe
public void onAction(Action action) {
switch (action.getType()) {
case ShowActions.TODO_SHOW:
showText = (String) action.getData().get(ShowActions.GET_TEXT);
Log.i("showText", showText);
emitStoreChange();
break;
default:
break;
}
}
public String getShowText() {
return showText;
}
@Override
StoreChangeEvent changeEvent() {
return new ShowChangeEvent();
}
public class ShowChangeEvent implements StoreChangeEvent { }
}
@Subscribe
public void showText(ShowStore.ShowChangeEvent event) {
mTextView.setText(mShowStore.getShowText());
}
View 的事件攜帶資料,交給 ActionsCreator 建立帶 type 的 Action;實際的分發發生在 Dispatcher.dispatch 中;訂閱了該 Action 的 Store 接手,在這裡完成各種邏輯處理,甚至發起網路請求;處理完畢後把結果封裝成一個事件,透過 emitChange 再次經過調度器送出;訂閱該事件的函式(定義在 View 中)收到後更新介面。
價值在於可預測性:資料只往一個方向流,任何狀態變化都能沿著 Action → Store → ChangeEvent 這條路回溯,測試時只要餵入 Action 並檢查 Store 狀態即可,不必操作 UI。代價是樣板程式碼變多——一個小功能要動到 Action、Creator、Dispatcher、Store、Event 五個地方。
另外要留意範例中 Dispatcher 與各 Store 都用單例實作,這在測試時會造成狀態殘留,正式專案建議加上 reset 機制或改用依賴注入管理生命週期。而在現代 Android 開發中,Otto 已停止維護,可改用 LiveData/StateFlow 搭配 ViewModel 來達到同樣的單向資料流效果,概念完全相通。
Android MVP 入門實作:把邏輯從 Activity 裡拆出來
先看專案結構: 可以歸納出一個規律:每個功能模組都由四個部分組成: XXActivity:負責畫面與使用者互動(View 層) XXView(Interface):
Android Studio 開發環境貼身配置指南:從主題到快捷鍵一次搞定
界面設置 默認的 Android Studio 採用灰色界面,如果你偏愛炫酷的黑色風格,可以這樣調整。 Settings-->Appearance-->The
Android VideoView 播放視頻完整教學
VideoView 是什麼VideoView 是 Android 提供的視頻播放元件,使用方式與 ImageView 類似。ImageView 負責顯示圖片,而 Vide
百度地圖應用骨架篇:一次建立 25 個範例的執行環境與專案結構
要一次學會 25 個地圖功能,最有效率的做法就是把它們放進同一個專案裡——這樣只需申請一把密鑰,也不必每個範例都重頭建專案。本文帶你把專案骨架搭好,從資源、SDK 初始化