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

Android 開發:如何移除 EditText 上的輸入焦點

編輯:進階開發

當畫面裡同時有 EditText 或 AutoCompleteTextView 時,視圖一載入,輸入焦點往往會自動跳到第一個輸入框,鍵盤也跟著彈出來。這在只是想讓使用者先看頁面的場景下顯得很打擾。

原始布局大致如下:

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/EditText01"
        android:hint="@string/hint"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="">
    </EditText>

    <Button
        android:id="@+id/Button02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_text">
    </Button>
</LinearLayout>

要讓焦點不要落在輸入框上,最省事的做法是在布局的父容器加上 android:focusable="true" 與 android:focusableInTouchMode="true",讓容器本身搶下焦點:

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:focusable="true"
    android:focusableInTouchMode="true">
    ...
</LinearLayout>

效果如下:

不必寫任何 Java 程式碼就把焦點移開了,這大概是最簡單的解法。如果頁面上有多個可聚焦元件干擾,也可以在 onCreate 裡對特定 view 呼叫 requestFocus() 明確指定初始焦點。

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