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

Android 入門實作:做一個人品計算器,學會 Activity 間資料傳遞

編輯:關於 Android 程式設計

這個小專案看起來只是玩笑,但它把幾個入門關鍵都練到了:控制項取值、表單驗證、Toast 提示、显式 Intent 跳轉、以及用 putExtra()/getXxxExtra() 在 Activity 之間傳遞資料。

第一個版面:輸入頁

activity_main.xml 需要一個輸入姓名的 EditText、一組單選的 RadioGroup,以及一顆觸發計算的按鈕:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/et_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="請輸入姓名" />

    <RadioGroup
        android:id="@+id/radioGroup1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <RadioButton android:id="@+id/rb_male"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="男" />
        <RadioButton android:id="@+id/rb_female"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="女" />
        <RadioButton android:id="@+id/rb_other"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="其他" />
    </RadioGroup>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="計算" />
</LinearLayout>

第二個版面:結果頁

activity_result.xml 用三個 TextView 分別放姓名、性別與結果評語:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView android:id="@+id/tv_name"   android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <TextView android:id="@+id/tv_sex"    android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <TextView android:id="@+id/tv_result" android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

MainActivity:驗證與跳轉

點擊事件的處理流程分四步:取值 → 驗證 → 判斷選項 → 跳轉並附帶資料。

public void click(View v) {
    // [1] 取得使用者名稱
    String name = et_name.getText().toString().trim();

    // [2] 空值檢查
    if (TextUtils.isEmpty(name)) {
        Toast.makeText(this, "請輸入姓名", Toast.LENGTH_SHORT).show();
        return;
    }

    // [3] 判斷選擇的性別
    int radioId = rg_group.getCheckedRadioButtonId();
    int sex = 0;
    switch (radioId) {
        case R.id.rb_male:   sex = 1; break;
        case R.id.rb_female: sex = 2; break;
        case R.id.rb_other:  sex = 3; break;
    }
    if (sex == 0) {                       // 一個都沒選
        Toast.makeText(this, "請選擇性別", Toast.LENGTH_SHORT).show();
        return;
    }

    // [4] 跳轉並傳遞資料
    Intent intent = new Intent(this, ResultActivity.class);
    intent.putExtra("name", name);
    intent.putExtra("sex", sex);
    startActivity(intent);
}

幾個值得留意的細節:trim() 去掉前後空白再驗證,比直接判空嚴謹;getCheckedRadioButtonId() 在沒有任何選項被選時會回傳 -1,因此「一個都沒選」的情況必須顯式處理;android:onClick 屬性要求方法簽名必須是 public void 且只接受一個 View 參數,寫錯會在執行期才發現。

ResultActivity:接收與計算

Intent intent = getIntent();
String name = intent.getStringExtra("name");
int sex = intent.getIntExtra("sex", 0);   // 第二個參數是取不到時的預設值

tv_name.setText(name);

取值時有一個小技巧:傳遞時是什麼型別,接收時就用對應的 getXxxExtra(),型別不匹配會拿到預設值而不報錯,這種 bug 特別難查。

接著依性別選擇不同的編碼方式,把姓名轉成位元組陣列:

byte[] bytes = null;
switch (sex) {
    case 1: tv_sex.setText("男");   bytes = name.getBytes("gbk");        break;
    case 2: tv_sex.setText("女");   bytes = name.getBytes("utf-8");      break;
    case 3: tv_sex.setText("其他"); bytes = name.getBytes("iso-8859-1"); break;
}

這裡有個實務提醒:getBytes() 會拋 UnsupportedEncodingException,必須用 try-catch 包住。範例中省略了它以聚焦主流程,但實際專案裡不可省略;StandardCharsets.UTF_8 是 Android 上更安全的選擇,因為它不會拋例外。

最後把位元組逐個累加,取絕對值後對 100 取餘得到分數:

int total = 0;
for (byte b : bytes) {
    total += (b & 0xff);        // 無號化,避免負數干擾
}

int score = Math.abs(total) % 100;
if (score > 90)      tv_result.setText("人品極佳");
else if (score > 80) tv_result.setText("人品還不錯");
else if (score > 60) tv_result.setText("剛剛及格");
else                 tv_result.setText("需要努力");

b & 0xff 這步不能省。Java 的 byte 是有號的,直接累加會讓結果出現負數,後面的取餘跟比較全部失準。

別忘了註冊 Activity

ResultActivity 必須在 AndroidManifest 中宣告,否則跳轉時會直接拋 ActivityNotFoundException:

<activity android:name=".ResultActivity" />

執行結果

這個範例真正教會我們的事

撇開玩笑性質的評語,這支小程式的骨架是無數商用 App 的縮影:表單輸入 → 前端驗證 → 資料打包 → 跨元件傳遞 → 結果呈現。把這條鏈路走順,後續要換成 Bundle、Parcelable 或 ViewModel 共享資料,都只是同一個思路的延伸。

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