iT邦幫忙

2025 iThome 鐵人賽

DAY 12
0
Mobile Development

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

Day12- App 的短期記憶!輕量資料儲存 (SharedPreferences)

  • 分享至 

  • xImage
  •  

在第十一天,你已經學會了如何使用 Material Design 的樣式系統,讓你的 App 不僅功能強大,外觀也更加美觀。
但你可能會發現一個問題:如果你做了一個 App 讓使用者可以調整設定,例如調整文字大小,當你關閉 App 再重新開啟時,這些設定又會回到最初的狀態。

這時,我們就需要一個 App 的「記憶」功能,讓 App 可以記住一些簡單的資料。這就是我們今天的重點:SharedPreferences

什麼是 SharedPreferences

  • 簡單比喻SharedPreferences 就是 App 的 「便利貼」「小筆記本」
    • 它是一個輕量級的資料儲存工具,適合用來儲存簡單的資料,像是:
      • 使用者的設定 (例如:深色模式、文字大小)。
      • 登入狀態 (例如:是否已登入)。
      • 小遊戲的最高分數。
  • 主要特性
    • 儲存的資料會以 「鍵值對 (Key-Value Pair)」 的方式存放。
    • 這些資料會被儲存在 App 的內部,即使 App 關閉或手機重開機,資料也不會消失。

程式碼實作:打造一個「文字大小記憶 App」

今天,我們要製作一個 App:使用者可以透過滑桿調整文字大小,即使關閉 App,下次開啟時,文字大小依然會維持上次的設定!

1. 修改你的 activity_main.xml

打開你的「設計圖」檔案 activity_main.xml。我們需要一個 TextView 和一個 SeekBar

  • TextView 的 ID 設為 myTextSeekBar 的 ID 設為 sizeSeekBar
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/myText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World"
        android:textSize="20sp"
        app:layout_constraintBottom_toTopOf="@+id/sizeSeekBar"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_chainStyle="packed" />

    <SeekBar
        android:id="@+id/sizeSeekBar"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="32dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="32dp"
        android:max="100"
        android:progress="20"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/myText" />

</androidx.constraintlayout.widget.ConstraintLayout>

2. 修改你的 MainActivity.java

打開你的「操作說明書」檔案 MainActivity.java。我們需要告訴 App,在啟動時讀取「便利貼」裡的資料,並在滑桿被調整時,將新的數值寫回「便利貼」。

import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences; // 匯入 SharedPreferences 類別
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private TextView myText;
    private SeekBar sizeSeekBar;
    private SharedPreferences sharedPreferences;

    // 定義一個用來儲存文字大小的鍵值名稱
    private static final String FONT_SIZE_KEY = "font_size";

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

        // 1. 找到所有元件
        myText = findViewById(R.id.myText);
        sizeSeekBar = findViewById(R.id.sizeSeekBar);

        // 2. 準備好你的「便利貼」
        // 檔名叫做 "my_app_settings"
        sharedPreferences = getSharedPreferences("my_app_settings", MODE_PRIVATE);

        // 3. 讀取「便利貼」裡的資料
        // getInt(鍵值名稱, 預設值)
        int savedFontSize = sharedPreferences.getInt(FONT_SIZE_KEY, 20); // 如果找不到,就用預設值 20
        myText.setTextSize(savedFontSize);
        sizeSeekBar.setProgress(savedFontSize);

        // 4. 設定 SeekBar 的監聽器
        sizeSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                myText.setTextSize(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 5. 當使用者放開滑桿時,將新的數值寫回「便利貼」
                SharedPreferences.Editor editor = sharedPreferences.edit();
                // putInt(鍵值名稱, 要儲存的數值)
                editor.putInt(FONT_SIZE_KEY, seekBar.getProgress());
                editor.apply(); // 儲存資料
                
                Toast.makeText(MainActivity.this, "設定已儲存!", Toast.LENGTH_SHORT).show();
            }
        });
    }
}`
  • 程式碼解釋
    • getSharedPreferences(...):這行程式碼讓我們取得一個名為 my_app_settings 的「便利貼」。
    • editor = sharedPreferences.edit():要寫入資料,必須先取得一個 Editor 物件。
    • editor.putInt(...):這行程式碼將一個整數資料,用 FONT_SIZE_KEY 這個「鍵值名稱」儲存起來。
    • editor.apply():這行程式碼才是真正將資料寫入「便利貼」的動作。

3. 執行你的 App!

  • 點擊綠色的「」按鈕,執行你的 App。
  • 試著調整滑桿,然後完全關閉 App。
  • 再次開啟 App,你會發現文字大小依然維持在你上次設定的數值!
    day12

今日總結

今天我們學會了如何使用 SharedPreferences 這個強大的工具,讓 App 擁有「短期記憶」的功能。這是一個 App 開發中非常基礎且重要的功能。

明天,我們要學習另一個處理資料的重要工具:HashMap。它就像是 App 的「快速字典」,可以讓我們更有效率地處理資料!

明天見!


上一篇
Day11- Material Design 與樣式應用
系列文
Android 開發者養成計畫:從程式邏輯到作品集實戰12
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言