iT邦幫忙

2025 iThome 鐵人賽

DAY 13
0
Mobile Development

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

Day13- App 的快速字典!鍵值對集合 (HashMap)

  • 分享至 

  • xImage
  •  

在第十二天,學會了如何使用 SharedPreferences,讓你的 App 擁有「短期記憶」的功能,這是一個很重要的里程碑。

SharedPreferences 只適合儲存簡單的資料。如果我們需要儲存和管理更複雜、數量更多的資料,就需要另一個更強大的工具,也就是今天的重點:HashMap

什麼是 HashMap

  • 簡單比喻HashMap 就是 App 的 「快速字典」
    • 在字典裡,我們是透過**「單字」(Key,鍵)來找到「解釋」**(Value,值)。
    • HashMap 也是一樣,它會將資料以 「鍵值對 (Key-Value Pair)」 的方式儲存起來。
    • 你只需要提供「鍵」,就能在極短的時間內找到對應的「值」。
  • 用途
    • 儲存聯絡人資料,用「姓名」(鍵)來找「電話號碼」(值)。
    • 儲存商品資訊,用「商品編號」(鍵)來找「商品名稱」(值)。
    • 在程式解題中,用來快速查找對應關係,例如羅馬數字轉換。

程式碼實作:打造一個「快速查字典 App」

今天,我們要製作一個 App:當使用者輸入一個顏色名稱,按下按鈕後,App 就會顯示出這個顏色的英文!

1. 修改你的 activity_main.xml

打開你的「設計圖」檔案 activity_main.xml。我們需要一個 EditText 讓使用者輸入中文顏色、一個 Button 觸發查詢、和一個 TextView 顯示查到的英文。

<?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">

    <EditText
        android:id="@+id/colorInput"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="32dp"
        android:layout_marginTop="32dp"
        android:layout_marginEnd="32dp"
        android:hint="請輸入顏色(例如:紅色)"
        android:minHeight="48dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/searchButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="查詢英文"
        app:layout_constraintEnd_toEndOf="@+id/colorInput"
        app:layout_constraintStart_toStartOf="@+id/colorInput"
        app:layout_constraintTop_toBottomOf="@+id/colorInput" />

    <TextView
        android:id="@+id/resultTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="查詢結果將顯示在這裡"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="@+id/searchButton"
        app:layout_constraintStart_toStartOf="@+id/searchButton"
        app:layout_constraintTop_toBottomOf="@+id/searchButton" />

</androidx.constraintlayout.widget.ConstraintLayout>`

2. 修改你的 MainActivity.java

打開你的「操作說明書」檔案 MainActivity.java。我們需要告訴 App,當 App 啟動時建立一個 HashMap,並在按鈕被點擊時,用 EditText 的內容作為「鍵」去查詢。

`import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    // 宣告一個 HashMap 來儲存顏色對應關係
    private HashMap<String, String> colorMap;

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

        // 1. 找到所有元件
        EditText colorInput = findViewById(R.id.colorInput);
        Button searchButton = findViewById(R.id.searchButton);
        TextView resultTextView = findViewById(R.id.resultTextView);

        // 2. 準備你的「快速字典」
        colorMap = new HashMap<>();
        colorMap.put("紅色", "Red");
        colorMap.put("藍色", "Blue");
        colorMap.put("綠色", "Green");
        colorMap.put("黃色", "Yellow");
        colorMap.put("黑色", "Black");
        colorMap.put("白色", "White");

        // 3. 設定按鈕的點擊監聽器
        searchButton.setOnClickListener(v -> {
            String inputColor = colorInput.getText().toString();

            // 檢查使用者是否有輸入
            if (inputColor.isEmpty()) {
                Toast.makeText(this, "請輸入顏色名稱!", Toast.LENGTH_SHORT).show();
                return;
            }

            // 4. 使用 HashMap 的 get() 方法,用鍵來查詢值
            String englishColor = colorMap.get(inputColor);

            // 5. 判斷是否有查到結果
            if (englishColor != null) {
                resultTextView.setText(englishColor);
            } else {
                resultTextView.setText("找不到該顏色!");
            }
        });
    }
}`
  • 程式碼解釋
    • HashMap<String, String>:宣告一個 HashMap,它的「鍵」和「值」都是 String (字串)。
    • colorMap.put("紅色", "Red"):使用 put() 方法,將「鍵」("紅色")和「值」("Red")存入字典。
    • colorMap.get(inputColor):使用 get() 方法,將使用者輸入的 inputColor 作為「鍵」,來查詢對應的「值」。

3. 執行你的 App!

  • 點擊綠色的「」按鈕,執行你的 App。
  • 試著在輸入框中輸入「紅色」,然後點擊「查詢英文」按鈕。
  • 你會看到 TextView 上顯示出正確的英文「Red」。

day13

今日總結

今天我們學會了:

  • HashMap 的概念,以及它在 App 中的應用。
  • 如何使用 HashMap<Key, Value> 宣告一個「字典」。
  • 如何使用 put() 方法來儲存資料。
  • 如何使用 get() 方法來查詢資料。

明天,將進入一個重要的實作練習:具備記憶功能的待辦清單 App。我們會結合前面學到的 RecyclerViewSharedPreferences 和今天的 HashMap 概念,來完成一個完整且實用的 App!

明天見!


上一篇
Day12- App 的短期記憶!輕量資料儲存 (SharedPreferences)
下一篇
Day14- 第二階段挑戰:具備記憶功能的待辦清單 App
系列文
Android 開發者養成計畫:從程式邏輯到作品集實戰14
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言