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

Activity 中點擊 Button 讓 EditText 失去焦點

編輯:關於 Android 程式設計

界面中有一個 EditText 和一個 Button,如何做到點擊 Button 時讓 EditText 失去焦點?直接看程式碼。

XML 佈局:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:text="點擊Button讓Editext失去焦點" />
</RelativeLayout>

Activity 程式碼:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mButton = (Button) findViewById(R.id.button);
    mEditText = (EditText) findViewById(R.id.editext);

    mEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean b) {
            if (!b) {
                Toast.makeText(MainActivity.this, "Editext失去焦點了", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(MainActivity.this, "Editext獲取焦點了", Toast.LENGTH_SHORT).show();
            }
        }
    });

    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mButton.setFocusable(true);
            mButton.setFocusableInTouchMode(true);
            mButton.requestFocus();
        }
    });
}

記得 Button 一定要設定那三行程式碼才會生效。當然,你也可以用下面兩行取代:

mButton.setFocusable(true);
mButton.requestFocusFromTouch();

另外,在 Button 監聽中也可以只寫一行 mButton.requestFocus();,但需在對應的 Button XML 中加上兩個參數 focusable 和 focusableInTouchMode:

<Button
    android:id="@+id/button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:text="點擊Button讓Editext失去焦點" />
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved