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

Android 學習筆記:EditText、TextView、Button 與選單欄實作

編輯:關於 Android 程式設計

這篇筆記做一個小練習:兩個輸入框、一個運算符號、一顆按鈕,按下後跳到結果頁顯示乘積,同時加上「關於」與「退出」兩個選單項。基本元件全都用上了。

一、主畫面 activity_main.xml

使用 RelativeLayout,透過 layout_below 讓元件依序往下排列。

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.activity_03.MainActivity">

    <EditText
        android:id="@+id/factor_one"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/symbol"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/factor_one" />

    <EditText
        android:id="@+id/factor_two"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/symbol" />

    <Button
        android:id="@+id/multiply"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/factor_two" />

</RelativeLayout>

二、結果頁 result.xml

<?xml version="1.0" encoding="utf-8"?>
<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/result"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

三、MainActivity.java

public class MainActivity extends ActionBarActivity {

    private EditText factor_one;
    private EditText factor_two;
    private TextView symbol;
    private Button multiply;

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

        factor_one = (EditText) findViewById(R.id.factor_one);
        factor_two = (EditText) findViewById(R.id.factor_two);
        symbol     = (TextView)  findViewById(R.id.symbol);
        multiply   = (Button)    findViewById(R.id.multiply);

        symbol.setText(R.string.symbol);
        multiply.setText("計算");

        multiply.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String factor_one_str = factor_one.getText().toString();
                String factor_two_str = factor_two.getText().toString();

                Intent intent = new Intent();
                intent.putExtra("factor_one_str", factor_one_str);
                intent.putExtra("factor_two_str", factor_two_str);
                intent.setClass(MainActivity.this, ResultActivity.class);
                MainActivity.this.startActivity(intent);
            }
        });
    }

    // 建立選單
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // MenuItem menu.add(int groupId, int itemId, int order, int titleRes)
        menu.add(0, 1, 1, R.string.about);
        menu.add(0, 2, 2, R.string.exit);
        return super.onCreateOptionsMenu(menu);
    }

    // 處理選單點擊
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == 1) {
            // 「關於」:此處可加上說明對話框
        } else if (item.getItemId() == 2) {
            // 「退出」
            finish();
        }
        return super.onOptionsItemSelected(item);
    }
}

四、ResultActivity.java

用 getIntent() 取出上一頁傳來的 extra,字串轉整數後相乘。

public class ResultActivity extends Activity {

    private TextView result;

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

        String factor_one_str = getIntent().getStringExtra("factor_one_str");
        String factor_two_str = getIntent().getStringExtra("factor_two_str");

        int factor_one = Integer.parseInt(factor_one_str);
        int factor_two = Integer.parseInt(factor_two_str);

        result = (TextView) findViewById(R.id.result);
        result.setText(factor_one * factor_two + "");
    }
}

五、strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Activity_03</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="symbol">乘以</string>
    <string name="exit">退出</string>
    <string name="about">關於</string>
</resources>

六、別忘了註冊 Activity

新增的 ResultActivity 必須在 AndroidManifest.xml 中登記,否則啟動時會拋出 ActivityNotFoundException:

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

七、這份練習涵蓋的觀念

  • 元件取得:findViewById() 搭配型別轉換,是每個 Activity 的起手式。
  • 事件綁定:setOnClickListener() 搭配匿名內部類別,適合簡單的單點回應。
  • 頁面跳轉與傳值:Intent.putExtra() 放資料,getIntent().getStringExtra() 取值。key 名稱必須一致,建議抽成常數避免打錯字。
  • 選單機制:onCreateOptionsMenu() 負責建立,onOptionsItemSelected() 負責分派。兩個方法成對出現,缺一不可。

這個範例的 Integer.parseInt() 沒有做例外處理,實務上使用者輸入空白或非數字時會直接崩潰。正式環境應該先用 TextUtils.isEmpty() 檢查,並用 try/catch 包住轉換。

歡迎大家訪問我的個人網站「萌萌的 IT 人」。

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