0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Android 9(Pie)以降で画面起動時に特定のViewに初期フォーカスを当てる方法

Last updated at Posted at 2019-11-14

今さっき知ったのですが(遅)、Android 9(Pie)でViewのフォーカスに関する仕様変更があり、タップモードにおいてActivityは初期フォーカスを暗黙的に指定しなくなっていました
この初期フォーカスが自動で当たる機能は入力フォーム画面や検索画面では便利で、使っていた方も多いのではないでしょうか。

Oreo以前であれば、以下のxmlを持つActivityが起動したとき、暗黙的にEditTextに初期フォーカスが当たっていましたが、Pie以降で同様のことを実現する場合、明示的に初期フォーカスを当てるViewを指定しなければならなくなりました

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- Android Pie以降ではsearchWindowに初期フォーカスが当たらない -->
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    ...

</androidx.constraintlayout.widget.ConstraintLayout>

手動で初期フォーカスを当てるViewを指定する方法は簡単で、**対象のViewに``をネストさせるだけ**です。
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- searchWindowに初期フォーカスが当たるようになる -->
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
        <requestFocus />
    </EditText>

    ...

</androidx.constraintlayout.widget.ConstraintLayout>

この<requestFocus />はOreo以前でも有効なので、対応としてはこれで十分だと思います。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?