起動時にEditTextにフォーカスさせない方法 | Androidアプリ開発

※当サイトはアフィリエイト広告を利用しています。

EditTextを含むActivityを作成し、
実行すると下図のようにEditTextにフォーカスされることがあります
(機種による?エミュレーターではフォーカスしない)

ここで鬱陶しいのがEditTextにフォーカスされることで、
起動時にいちいちキーボードが表示されることです。

この記事ではこの現象の対処方法を紹介します。
スポンサーリンク


起動時にEditTextにフォーカスさせない方法

さきほどのActivityのxmlは以下です。

activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".SecondaryActivity"
    >


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="↓↓↓起動時にEditTextにフォーカスされる"
        />

    <EditText
        android:layout_width="200dp"
        android:layout_height="50dp"
        android:inputType="numberDecimal"
        />

</LinearLayout>

では、このコードに対して、
起動時にEditTextにフォーカスさせないようにしていきましょう。


起動時にEditTextにフォーカスさせない方法は「EditTextよりも前のViewにフォーカスさせてしまう」です。
今回でいけばEditTextの前に設定されたTextViewにフォーカスさせてしまいます。

しかしながら、TextViewは通常はフォーカス不可ですので、
フォーカスを可能にする要素を追加する必要があります。

フォーカスを可能にする要素は以下です。
android:focusable="true"
android:focusableInTouchMode="true"

このコードを追加した最終的なサンプルコードは以下です。

activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".SecondaryActivity"
    >


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="↓↓↓起動時にEditTextにフォーカスされる"

        android:focusable="true"
        android:focusableInTouchMode="true"
        />

    <EditText
        android:layout_width="200dp"
        android:layout_height="50dp"
        android:inputType="numberDecimal"
        />


</LinearLayout>

これで起動時にEditTextにフォーカスすることはなくなります。

まとめ

この記事ではAndroidアプリ開発において、
起動時にEditTextにフォーカスさせない方法を紹介しました。

この現象で困っている方の参考になれば幸いです。