Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 小專案:標準體重測量儀,順手把 Bundle 傳值學會(附原始碼)

編輯:Android 開發實例

這次要做的東西很生活化:輸入身高、選擇性別,按下確定,跳到下一頁告訴你標準體重是多少。看似簡單,但它把「頁面之間怎麼傳資料」這個 Android 新手必經的關卡完整走了一遍。

版面準備

首頁放在 res/layout/main.xml,包含一個身高輸入框 EditText、一組性別單選 RadioGroup(含男、女兩個 RadioButton)以及一顆確認按鈕。第二頁放在 res/layout/mainlayout.xml,擺兩個 TextView 顯示結果,加一顆返回首頁的按鈕。

如果不想手寫 XML,早期可以用 DroidDraw 這類視覺化拖拉工具先把版型拉出來,再回頭微調。

第一頁:驗證、判斷、打包

public class BundleObject extends Activity {

    private Button mButton;
    private EditText mEditText;
    private RadioGroup mRadioGroup;
    private double height;
    private String Sex;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mButton = (Button) findViewById(R.id.confirm);
        mButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {

                mEditText = (EditText) findViewById(R.id.heigt);

                // 沒填身高就攔下來
                if (mEditText.getText().toString().length() == 0) {
                    new AlertDialog.Builder(BundleObject.this)
                            .setMessage("請輸入您的身高")
                            .setTitle("提示")
                            .setNeutralButton("確定",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(
                                            DialogInterface dialog, int which) {
                                        mEditText.setHighlightColor(Color.RED);
                                    }
                                })
                            .create()
                            .show();
                    return;
                }

                mRadioGroup = (RadioGroup) findViewById(R.id.sex);
                height = Double.parseDouble(mEditText.getText().toString());
                Sex = (mRadioGroup.getCheckedRadioButtonId() == R.id.M) ? "M" : "F";

                // 打包資料,交給下一頁
                Intent intent = new Intent();
                intent.setClass(BundleObject.this, Next.class);

                Bundle bun = new Bundle();
                bun.putDouble("Height", height);
                bun.putString("Sex", Sex);
                intent.putExtras(bun);

                startActivity(intent);
                BundleObject.this.finish();
            }
        });
    }
}

這裡有個容易踩的細節:AlertDialog.Builder() 在 Android 1.5 以上的版本要傳入「類名.this」,例如 AlertDialog.Builder(BundleObject.this);1.5 以下直接寫 this 就可以了。

傳值的核心概念是:Bundle 是一個鍵值袋。putDouble、putString 把資料依鍵名放進去,intent.putExtras() 把袋子掛到 Intent 上,startActivity() 出發,finish() 順手關掉自己,避免返回鍵又回到舊頁面。

第二頁:拆袋、計算、顯示

public class Next extends Activity {

    private TextView mTextView01, mTextView02;
    private Button mButton1;
    private String Sex, SextText;
    private double Height;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mainlayout);

        // 用同一組鍵名把資料取出來
        Bundle bun = this.getIntent().getExtras();
        Sex = bun.getString("Sex");
        Height = bun.getDouble("Height");

        SextText = Sex.equals("M") ? "男性" : "女性";
        String Weight = getWeight(Sex, Height);

        mTextView01 = (TextView) findViewById(R.id.TextView01);
        mTextView02 = (TextView) findViewById(R.id.TextView02);
        mTextView01.setText("您是一位" + SextText + ",您的身高為:" + Height + "cm");
        mTextView02.setText("您的標准體重為:" + Weight + "千克");

        mButton1 = (Button) findViewById(R.id.Button03);
        mButton1.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(Next.this, BundleObject.class);
                startActivity(intent);
                Next.this.finish();
            }
        });
    }

    // 取標準體重,四捨五入到小數兩位
    public String getWeight(String Sex, double height) {
        String Weight;
        if (Sex.equals("M")) {
            Weight = format((height - 80) * 0.7);
        } else {
            Weight = format((height - 70) * 0.6);
        }
        return Weight;
    }

    private String format(double num) {
        NumberFormat formatter = new DecimalFormat("0.00");
        return formatter.format(num);
    }
}

反過來看就很清楚:第一頁用 Bundle 打包,第二頁就用 getIntent().getExtras() 拆開,鍵名必須一致,型別也要對得上(putDouble 對 getDouble、putString 對 getString)。

別忘了配置檔

這是最常被忽略、也最難自己 debug 的一環:凡是新增的 Activity,都必須在 AndroidManifest.xml 裡明確宣告,否則程式在跳頁那一步就會直接崩潰。

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".BundleObject" android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".Next"></activity>
</application>

這個 AndroidManifest.xml 的角色,有點像 ASP.NET 的 web.config——應用元件的清單、權限、啟動入口都在這裡登記。只有第一個頁面需要 intent-filter,因為它是啟動點;其餘頁面單純宣告 android:name 即可。

到這裡,一個能跨頁傳值、帶輸入驗證的小工具就完成了。你會發現,日後只要遇到「A 頁面要把資料交給 B 頁面」,思路都是同一套:打包、掛上 Intent、出發、拆開。

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