首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Android EditText 默認不獲取焦點:在佈局根節點設置 focusableInTouchMode

     編輯:程式設計疑難解答

現象

Activity/Fragment 含 `EditText`,啟動時鍵盤彈出、光標閃爍,體驗不佳。

解決:父佈局搶焦點

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:focusable="true"
    android:focusableInTouchMode="true">  

    <EditText
        android:id="@+id/et_input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="請輸入" />
</LinearLayout>

原理

  • View 焦點遞歸查找:`focusableInTouchMode=true` 的 View 優先獲得初始焦點。
  • 父佈局(`LinearLayout`/`RelativeLayout`/`ConstraintLayout` 等)默認 `focusable=false`,設置為 `true` 後成為焦點「黑洞」。

替代方案(代碼控制)

// 在 onCreate / onViewCreated 中
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); // 隱藏鍵盤
rootView.requestFocus(); // 手動請求焦點給根佈局

注意

  • 若佈局含 `ListView`/`RecyclerView`,需在其父容器設置,避免列表項搶焦點。
  • Dialog/BottomSheet 同理,在其根 View 設置 `focusableInTouchMode`。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved