iT邦幫忙

2025 iThome 鐵人賽

DAY 14
0
Mobile Development

Android 開發者養成計畫:從程式邏輯到作品集實戰系列 第 14

Day14- 第二階段挑戰:具備記憶功能的待辦清單 App

  • 分享至 

  • xImage
  •  

來到鐵人賽的第十四天,我們將把前面學到的所有知識,串聯成一個完整的 App!

今天我們要製作一個「待辦清單 App」,它不只可以讓你新增待辦事項,更重要的是,即使你關掉 App,下次再打開,清單內容也不會消失! 這就是 SharedPreferences 的魔力。

這個專案,就是一個結合了 EditTextButtonRecyclerViewSharedPreferences 的綜合實作。

程式解題:簡易待辦清單

  • 題目說明
    • 建立一個 App,可以讓使用者輸入待辦事項。
    • 新增的事項會顯示在一個可滾動的清單中。
    • 這個清單的內容,必須被保存下來。當 App 關閉後再重新開啟,清單上的所有事項都應該依然存在。

實作時間:打造你的「待辦清單 App」

1. 修改你的 activity_main.xml

打開你的「設計圖」檔案 activity_main.xml。我們需要一個 EditText 讓使用者輸入事項、一個 Button 觸發新增、和一個 RecyclerView 顯示待辦清單。

你可以運用 LinearLayoutConstraintLayout 把這些元件排版好。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/todoInput"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="輸入待辦事項"
            android:minHeight="48dp" />

        <Button
            android:id="@+id/addButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="新增" />
    </LinearLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/todoRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginTop="16dp"
        android:layout_weight="1" />

</LinearLayout>`

2. 修改 MyAdapter.javalist_item.xml

這些檔案沿用我們在第八天和第九天建立的,不用做太大變動。只需要確保 list_item.xml 中的 TextViewid,且 MyAdapter 能正確地接收並顯示 String 清單。

3. 修改你的 MainActivity.java

這是最關鍵的部分。我們需要:

  1. 在啟動時,從 SharedPreferences 讀取之前保存的清單。
  2. 在點擊「新增」按鈕時,將新的事項加入清單,並保存到 SharedPreferences
  3. 使用 Gson 函式庫來幫助我們將清單轉換成 String 格式,以便儲存。

首先,你需要在 build.gradle (Module: app) 檔案的 dependencies 區塊,加入 Gson 函式庫:

`dependencies {
    // ... 其他 dependencies ...
    implementation 'com.google.code.gson:gson:2.8.9' // 新增這一行
}`

然後點擊右上角的 Sync Now

以下是完整的 MainActivity.java 程式碼:

`import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private EditText todoInput;
    private Button addButton;
    private RecyclerView todoRecyclerView;
    private MyAdapter todoAdapter;
    private List<String> todoList;
    private SharedPreferences sharedPreferences;

    private static final String PREFS_NAME = "MyTodoPrefs";
    private static final String TODO_LIST_KEY = "todo_list";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 1. 找到所有元件
        todoInput = findViewById(R.id.todoInput);
        addButton = findViewById(R.id.addButton);
        todoRecyclerView = findViewById(R.id.todoRecyclerView);

        // 2. 取得 SharedPreferences 實例
        sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);

        // 3. 讀取儲存的清單
        loadTodoList();

        // 4. 設定 RecyclerView
        todoAdapter = new MyAdapter(todoList);
        todoRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        todoRecyclerView.setAdapter(todoAdapter);

        // 5. 設定按鈕的點擊監聽器
        addButton.setOnClickListener(v -> {
            String todoItem = todoInput.getText().toString();
            if (!todoItem.isEmpty()) {
                todoList.add(todoItem);
                todoAdapter.notifyItemInserted(todoList.size() - 1); // 通知 Adapter 有新資料
                saveTodoList(); // 保存清單到 SharedPreferences
                todoInput.setText(""); // 清空輸入框
            }
        });
    }

    // 讀取清單資料的方法
    private void loadTodoList() {
        Gson gson = new Gson();
        String json = sharedPreferences.getString(TODO_LIST_KEY, null);
        Type type = new TypeToken<ArrayList<String>>() {}.getType();
        todoList = gson.fromJson(json, type);

        if (todoList == null) {
            todoList = new ArrayList<>();
        }
    }

    // 保存清單資料的方法
    private void saveTodoList() {
        Gson gson = new Gson();
        String json = gson.toJson(todoList);
        sharedPreferences.edit().putString(TODO_LIST_KEY, json).apply();
    }
}`
  • 程式碼解釋
    • Gson:這是個強大的函式庫,可以幫助我們將 Java 的清單 (List) 物件,輕鬆地轉換成文字 (String) 格式,以便儲存到 SharedPreferences
    • loadTodoList():這個方法負責從 SharedPreferences 讀取資料,並用 Gson 將文字轉回清單物件。
    • saveTodoList():這個方法負責將目前的清單,用 Gson 轉換成文字,並儲存到 SharedPreferences

3. 執行你的 App!

  • 點擊綠色的「」按鈕,執行你的 App。
  • 輸入待辦事項,點擊新增。
  • 關閉 App(從後台完全關閉),再重新開啟。
  • 你會發現,你新增的事項都還在!

恭喜你!已經完成了第一個具備「記憶」功能的待辦清單 App,這是一個非常實用的作品!

day14

今日總結

今天我們學會了:

  • 如何將 EditTextButtonRecyclerViewSharedPreferences 整合到一個 App 中。
  • 如何使用 Gson 函式庫來解決 SharedPreferences 無法儲存清單的問題。
  • 成功完成一個具備「資料持久化」功能的 App。

接下來,將進入一個全新的階段:程式碼架構。我們會學習 MVVM 這兩種專業的開發模式,讓你的程式碼結構更清晰、更容易維護。

明天見!


上一篇
Day13- App 的快速字典!鍵值對集合 (HashMap)
系列文
Android 開發者養成計畫:從程式邏輯到作品集實戰14
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言