Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 待辦事項 ToDo 應用實現解析

編輯:關於 Android 程式設計

這個 ToDo 是從 MediaTek 項目中剝離出來的一份完整代碼,功能不算花哨,但結構相當規範,很適合拿來學習「列表 + 多選 + ActionMode + 分組」這一套組合拳。完整代碼可以在我的 GitHub 上找到。

整體架構

主要由幾個角色構成:

  • TodoActivity——主界面,負責列表展示與交互調度;
  • TodoListAdapter——自定義適配器,內部同時管理「待辦」和「已完成」兩個分組;
  • EditTodoActivity——新增 / 編輯 / 查看詳情的獨立頁面;
  • TimeChangeReceiver——監聽日期變化,用於自動切換「今天 / 逾期」狀態。

核心常量與成員

public class TodoActivity extends Activity {

    private static final String TAG = "TodosActivity";

    private static final int REQUEST_ADD_NEW = 1;
    private static final int REQUEST_SHOW_DETAILS = REQUEST_ADD_NEW + 1;
    private static final int DIALOG_DELETE_ITEMS = 1;

    private boolean mShowingDialog = false;
    private TimeChangeReceiver mTimeChangeReceiver = null;

    private TextView mNumberTextView;
    private MenuItem mBtnChangeState;
    private MenuItem mBtnDelete;

    private TodoListAdapter mTodoListAdapter = null;
    private ListView mTodosListView = null;
    private AdapterViewListener mAdapterViewListener = null;

    private ActionMode mActionMode = null;
    private TodosActionModeCallBack mTodosActionCallBack = new TodosActionModeCallBack();

請求碼用「上一個 + 1」的方式定義,是一個避免魔法數字的小技巧。

初始化與生命周期

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.items);

    initViews();
    configureActionBar();

    mTimeChangeReceiver = TimeChangeReceiver.registTimeChangeReceiver(this);
    mTimeChangeReceiver.addDateChangeListener(mTodoListAdapter);
}

private void initViews() {
    mTodoListAdapter = new TodoListAdapter(this);
    mAdapterViewListener = new AdapterViewListener();

    mTodosListView = (ListView) findViewById(R.id.list_todos);
    mTodosListView.setAdapter(mTodoListAdapter);
    mTodosListView.setOnItemClickListener(mAdapterViewListener);
    mTodosListView.setOnItemLongClickListener(mAdapterViewListener);
}

把 click 和 longClick 的監聽器合併成一個類,實現 AdapterView.OnItemClickListener 與 OnItemLongClickListener 兩個接口。好處是兩個回調可以共享狀態判斷邏輯,比如「當前是否處於編輯模式」。

@Override
protected void onResume() {
    super.onResume();
    // 從其他頁面返回時,若之前有未關閉的對話框,重新彈出
    if (mShowingDialog) {
        showDialog(DIALOG_DELETE_ITEMS);
    }
}

@Override
protected void onPause() {
    if (mShowingDialog) {
        removeDialog(DIALOG_DELETE_ITEMS);
    }
    super.onPause();
}

@Override
protected void onDestroy() {
    mTimeChangeReceiver.clearChangeListener();
    unregisterReceiver(mTimeChangeReceiver);
    super.onDestroy();
}

mShowingDialog 這個標志位值得學習。Android 中 Dialog 由 Activity 管理,Activity 進入後台再回來時 dialog 可能已經失效,用標志位配合 onResume / onPause 重新管理,能避免 BadTokenException。另外 registerReceiver 一定對應 unregisterReceiver,否則是內存洩漏。

返回鍵與編輯模式

@Override
public void onBackPressed() {
    if (mTodoListAdapter.isEditing()) {
        updateToEditNull();   // 先退出編輯模式,而非直接退出 Activity
        return;
    }
    super.onBackPressed();
}

private void updateToEditNull() {
    if (mActionMode != null) {
        mActionMode.finish();
    }
    invalidateOptionsMenu();
    mTodoListAdapter.setEditingType(TodoListAdapter.EDIT_NULL);
}

這是「層級式返回」的標準做法:多選模式下按返回先取消多選,再按一次才退出頁面。很多 App 忽略這一點,導致用戶誤觸返回就丟失了編輯狀態。

onActivityResult:統一處理三種操作結果

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    TodoInfo info = null;

    switch (resultCode) {
        case Utils.OPERATOR_INSERT:
            info = (TodoInfo) data.getSerializableExtra(Utils.KEY_PASSED_DATA);
            mTodoListAdapter.addItem(info);
            mTodosListView.setSelection(mTodoListAdapter.getItemPosition(info));
            break;

        case Utils.OPERATOR_UPDATE:
            info = (TodoInfo) data.getSerializableExtra(Utils.KEY_PASSED_DATA);
            if (null == info) {
                LogUtils.e(TAG, "result: OPERATOR_UPDATE, but data is null");
                return;
            }
            mTodoListAdapter.updateItemData(info);
            mTodosListView.setSelection(mTodoListAdapter.getItemPosition(info));
            break;

        case Utils.OPERATOR_DELETE:
            info = (TodoInfo) data.getSerializableExtra(Utils.KEY_PASSED_DATA);
            if (null == info) {
                LogUtils.e(TAG, "result: OPERATOR_DELETE, but data is null");
                return;
            }
            mTodoListAdapter.removeItem(info);
            break;

        default:
            break;
    }
}

這裡有兩個設計亮點:

  1. 用 resultCode 而非 requestCode 分流。因為「新增」和「查看詳情」用的是同一個 Activity,區分「用戶做了什麼」比區分「從哪來的」更自然。
  2. setSelection() 定位到操作項。新增或編輯後自動滾到該項,是一個很小但體驗提升明顯的細節。

同時注意每個分支都做了 null 判斷。通過 Intent 傳遞 Serializable 對象時,如果序列化過程出問題,取回來就是 null,不做防禦會直接 NPE。

删除確認對話框

@Override
protected Dialog onCreateDialog(int id) {
    AlertDialog dialog = null;
    switch (id) {
        case DIALOG_DELETE_ITEMS:
            dialog = new AlertDialog.Builder(this)
                    .setTitle(R.string.delete)
                    .setMessage(R.string.delete_selected_items)
                    .setIconAttribute(android.R.attr.alertDialogIcon)
                    .create();

            dialog.setButton(DialogInterface.BUTTON_NEGATIVE, getText(R.string.cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mShowingDialog = false;
                        }
                    });

            dialog.setButton(DialogInterface.BUTTON_POSITIVE, getText(R.string.delete),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mTodoListAdapter.deleteSelectedItems();
                            updateToEditNull();
                            updateBottomBarWidgetState();
                            mShowingDialog = false;
                        }
                    });

            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                public void onCancel(DialogInterface dialog) {
                    mShowingDialog = false;
                }
            });
            return dialog;

        default:
            break;
    }
    return super.onCreateDialog(id);
}

提示文案會根據選中數量動態變化,這是 onPrepareDialog 的職責:

@Override
protected void onPrepareDialog(int id, Dialog dialog) {
    super.onPrepareDialog(id, dialog);
    switch (id) {
        case DIALOG_DELETE_ITEMS:
            String msg = "";
            if (mTodoListAdapter.getEditType() == TodoListAdapter.EDIT_TODOS) {
                msg = mTodoListAdapter.getSeletedTodosNumber() > 1
                        ? getString(R.string.delete_selected_items)
                        : getString(R.string.delete_item);
            } else if (mTodoListAdapter.getEditType() == TodoListAdapter.EDIT_DONES) {
                msg = mTodoListAdapter.getSeletedDonesNumber() > 1
                        ? getString(R.string.delete_selected_items)
                        : getString(R.string.delete_item);
            }
            ((AlertDialog) dialog).setMessage(msg);
            break;
        default:
            break;
    }
}

onCreateDialog 只執行一次,onPrepareDialog 每次顯示前都會執行——把「變化」的部分放在後者,這是官方設計意圖。註意這套 showDialog / onCreateDialog 機制在 API 26 起已被標記為 deprecated,新項目應改用 DialogFragment。

底部操作欄狀態同步

void updateBottomBarWidgetState() {
    if (mTodoListAdapter.isEditing()) {
        int selectedNumber = 0;
        int dataSourceNumber = 0;

        if (mTodoListAdapter.getEditType() == TodoListAdapter.EDIT_TODOS) {
            selectedNumber = mTodoListAdapter.getSeletedTodosNumber();
            dataSourceNumber = mTodoListAdapter.getTodosDataSource().size();
        } else if (mTodoListAdapter.getEditType() == TodoListAdapter.EDIT_DONES) {
            selectedNumber = mTodoListAdapter.getSeletedDonesNumber();
            dataSourceNumber = mTodoListAdapter.getDonesDataSource().size();
        }

        if (dataSourceNumber == 0) {
            updateToEditNull();   // 分組空了,自動退出編輯模式
        } else {
            // 一項都沒選時禁用按鈕,避免用戶點了沒反應
            mBtnDelete.setEnabled(selectedNumber > 0);
            mBtnChangeState.setEnabled(selectedNumber > 0);
            mTodosActionCallBack.updateActionMode();
        }
    }
}

那段「一項都沒選就禁用按鈕」的邏輯,源碼裡還留著 MTK 的工程註釋 ///M: add to avoid this case。這是一個非常典型的用戶體驗細節:按鈕可點但點了沒反應,比按鈕置灰更令人困惑。

ActionMode 與多選

class TodosActionModeCallBack implements ActionMode.Callback {

    private Button mSelectionButton;
    private PopupMenu mSelectionMenu;

    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        mActionMode = mode;
        getMenuInflater().inflate(R.menu.list_edit, menu);
        mBtnChangeState = menu.findItem(R.id.btn_change_state);
        mBtnDelete = menu.findItem(R.id.btn_delete);
        startSelectionMode(mActionMode);
        return true;
    }

    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_select_all:
                mTodoListAdapter.allSelectAction(!mTodoListAdapter.isSelectedAll());
                updateBottomBarWidgetState();
                break;
            case R.id.btn_change_state:
                onChangeItemStateClick();
                updateBottomBarWidgetState();
                break;
            case R.id.btn_delete:
                showDialog(DIALOG_DELETE_ITEMS);
                mShowingDialog = true;
                break;
            default:
                break;
        }
        updateActionModeTitle();
        return true;
    }

    @Override
    public void onDestroyActionMode(ActionMode mode) {
        mActionMode = null;
        onBackPressed();   // 復用返回邏輯,順便退出編輯狀態
    }
}

onDestroyActionMode 中直接調用 onBackPressed() 是一個巧妙的復用——ActionMode 結束與按返回鍵,語義上都是「退出多選」,共用一套清理邏輯能避免狀態不一致。

ActionMode 標題顯示已選數量:

public void updateActionMode() {
    int num = getSelectedCount();
    String str = getResources().getString(R.string.selected_count);
    str = String.format(Locale.US, str, num);
    mSelectionButton.setText(str);
    updateSelectPopupMenu();
    if (mActionMode != null) {
        mActionMode.invalidate();
    }
}

private void updateChangeStateIcon(int editType) {
    if (editType == TodoListAdapter.EDIT_TODOS) {
        // 當前在「待辦」,按鈕表示「標記為已完成」
        mBtnChangeState.setIcon(R.drawable.todo_mark_done);
        mBtnChangeState.setTitle(R.string.mark_todo);
    } else if (editType == TodoListAdapter.EDIT_DONES) {
        mBtnChangeState.setIcon(R.drawable.todo_mark_todo);
        mBtnChangeState.setTitle(R.string.mark_done);
    }
}

註意 String.format 顯式傳了 Locale.US。不指定 Locale 時,在阿拉伯語等區域設置下數字格式化會出現在意料之外的結果,這是一個跨國產品必須注意的地方。

從這份代碼能學到什麼

  • 分組列表的建模:把「待辦 / 已完成」做成 Adapter 內部的一級分組,配合 header / footer 類型的 item,比嵌套 ListView 乾淨得多。
  • 編輯模式的狀態機:EDIT_NULL / EDIT_TODOS / EDIT_DONES 三態,加上返回鍵與 ActionMode 的聯動,覆蓋了大部分邊界情況。
  • 防禦式編程:處處可見的 null 判斷、空數據源判斷、選中數為 0 的按鈕禁用。
  • 可訪問性與本地化:字符串全部走 R.string,格式化指定 Locale。

如果要現代化改造,優先級最高的三件事是:Dialog 換 DialogFragment、數據層換 ViewModel + LiveData/Flow、ListView 換 RecyclerView 並用 MultiChoiceAdapter 模式重寫多選。但作為一份學習材料,它的結構依然清晰得恰到好處。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved