くわこのpermission denied.

WEBエンジニアの僕がぶつかった技術的な問題や発見

【Android】アプリ起動時にキーパッドが表示されるのを防ぐ方法

f:id:mask0702:20160117180731p:plain

Androidアプリを開発中、アプリ起動時にEditTextにフォーカスが当たってしまい、キーパッドが表示されてしまう問題を解決したので共有。

その方法は「起動時に、EditText以外にフォーカスが当たるようにする」というシンプルなもの。

layoutのxmlファイルでEditText以外の要素に
android:focusable="true"
android:focusableInTouchMode="true"
を追加して、requestFocus タグをその要素で挟めば良い。
例えばButtonタグにフォーカスを当てるにはこんな感じにすれば良い。

<EditText
    android:id="@+id/editText"
    android:layout_width="0dp"
    android:layout_weight="4"
    android:layout_height="wrap_content"
    android:inputType="text" />

<Button
    android:id="@+id/addButton"
    android:layout_width="0dp"
    android:layout_weight="1"
    android:layout_height="wrap_content"
    android:text="追加"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:onClick="addList"
    >
    <requestFocus />
</Button>

なるほど。

※参考
exiz.org