LoginSignup
6
3

More than 1 year has passed since last update.

EditTextを使うときは必ずimeOptionsを指定しよう

Posted at

EditText内でエンターキーを入力すると、通常はIME_ACTION_DONEというactionIdがlistenerに流れます。
が、EditTextの下に編集可能なUIが存在していた場合は、IME_ACTION_DONEではなくIME_ACTION_NEXTが呼ばれます。

なので、EditTextの配下に別のEditTextがない場合、以下コードのように「IME_ACTION_DONE」が来ることを前提として条件分岐をすることもあるかと思います。

      commentEditor.setOnEditorActionListener { _, actionId, _ ->
        if (actionId == EditorInfo.IME_ACTION_DONE) {
          /** コメント投稿処理 */
        }
        /** IME_ACTION_DONE以外の時は何もしない */
        true
      }

しかしながら、実は場合によっては、配下にEditTextや編集可能なUIが存在しなくても、IME_ACTION_NEXTが呼ばれてしまう場合もあるため、xmlで明確にエンター入力時のアクションを定義しておいた方が良いでしょう。 

            <EditText
                android:id="@+id/commentEditor"
                android:imeOptions="actionDone" ⇦これ
                android:layout_width="0dp"
                android:layout_height="wrap_content" />

これを指定しておかないと、例えばですが、「EditText上でエンターを押すとコメントを投稿する」という機能を実装していた場合、
EditTextの配下に何らかのUIを新規で配置しただけで、IME_ACTION_DONEが呼ばれず、
何度エンターを押してもコメントが投稿されないという不具合が発生してしまうリスクが発生してしまいます。

6
3
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
6
3