萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android EditText 編輯框完整使用教學與程式碼範例

前言

在 Android 應用程式開發中,EditText 是最常用的使用者輸入元件。本文將透過一個完整的登入畫面範例,詳細說明 EditText 的基本用法、屬性設定以及在 Activity 中處理輸入內容的技巧。

版面配置 (XML)

首先定義畫面版面,包含標題、帳號輸入框、密碼輸入框與確認按鈕:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="#000000"
        android:textSize="18sp"
        android:background="#00FF00"
        android:text="EditText 編輯框測試"
        android:gravity="center" />

    <EditText
        android:id="@+id/editview0"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="請輸入帳號"
        android:inputType="phone" />

    <EditText
        android:id="@+id/editview1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="請輸入密碼"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/editbutton0"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="確認" />

</LinearLayout>

Activity 程式碼實作

在 Activity 中取得元件參考,並為按鈕設定點擊監聽器以讀取輸入內容:

public class EditTextActivity extends Activity {
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.editview);
        mContext = this;

        final EditText editTextAccount = findViewById(R.id.editview0);
        final EditText editTextPassword = findViewById(R.id.editview1);
        Button btnConfirm = findViewById(R.id.editbutton0);

        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = editTextAccount.getText().toString().trim();
                String password = editTextPassword.getText().toString().trim();

                Toast.makeText(EditTextActivity.this, 
                    "用戶名:" + username + " 密碼:" + password, 
                    Toast.LENGTH_LONG).show();
            }
        });
    }
}

關鍵屬性說明

  • android:hint:提示文字,當輸入框為空時顯示。
  • android:inputType:指定輸入類型,如 "phone" 顯示數字鍵盤,"textPassword" 隱藏密碼。
  • getText().toString():取得使用者輸入的字串內容。
  • trim():移除字串首尾空白,避免誤判。

進階技巧

  • 使用 addTextChangedListener 即時監聽輸入變化。
  • 設定 android:maxLength 限制輸入長度。
  • 搭配 TextInputLayout 實現 Material Design 風格的浮動標籤與錯誤提示。

總結

EditText 是 Android 表單輸入的核心元件,掌握其屬性與事件處理能大幅提升使用者體驗。建議實際動手修改範例程式碼,體會不同 inputType 帶來的鍵盤變化。

copyright © 萬盛學電腦網 all rights reserved