來到鐵人賽的第十四天,我們將把前面學到的所有知識,串聯成一個完整的 App!
今天我們要製作一個「待辦清單 App」,它不只可以讓你新增待辦事項,更重要的是,即使你關掉 App,下次再打開,清單內容也不會消失! 這就是 SharedPreferences
的魔力。
這個專案,就是一個結合了 EditText
、Button
、RecyclerView
和 SharedPreferences
的綜合實作。
activity_main.xml
打開你的「設計圖」檔案 activity_main.xml
。我們需要一個 EditText
讓使用者輸入事項、一個 Button
觸發新增、和一個 RecyclerView
顯示待辦清單。
你可以運用 LinearLayout
或 ConstraintLayout
把這些元件排版好。
<?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>`
MyAdapter.java
和 list_item.xml
這些檔案沿用我們在第八天和第九天建立的,不用做太大變動。只需要確保 list_item.xml
中的 TextView
有 id
,且 MyAdapter
能正確地接收並顯示 String
清單。
MainActivity.java
這是最關鍵的部分。我們需要:
SharedPreferences
讀取之前保存的清單。SharedPreferences
。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
。恭喜你!已經完成了第一個具備「記憶」功能的待辦清單 App,這是一個非常實用的作品!
今天我們學會了:
EditText
、Button
、RecyclerView
和 SharedPreferences
整合到一個 App 中。Gson
函式庫來解決 SharedPreferences
無法儲存清單的問題。接下來,將進入一個全新的階段:程式碼架構。我們會學習 MVVM
這兩種專業的開發模式,讓你的程式碼結構更清晰、更容易維護。
明天見!