LoginSignup
5
7

More than 5 years have passed since last update.

戻るキーでEditTextのフォーカスをはずす

Last updated at Posted at 2017-04-09

IMEが表示されている状態ではActivity#onBackPressed()は呼ばれないのでここでEditTextのフォーカスを外すことはできません。
EditTextのフォーカスをはずすにはEditTextを拡張します:

MyEditText.java
package com.example.android.sampleapp;

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;

public class MyEditText extends EditText {
    public MyEditText(Context context) {
        super(context);
    }

    public MyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            View parent = (View) getParent();
            parent.setFocusable(true);
            parent.setFocusableInTouchMode(true);
            parent.requestFocus();
        }
        return super.onKeyPreIme(keyCode, event);
    }
}

注) Support Libraryを利用している場合は、AppCompat系のクラスを親クラスにすることが推奨されていたりします。例えばEditTextAppCompatEditTextです。

あとは適当にレイアウトxmlに追加すればokです。

ポイントは、

parent.setFocusable(true);
parent.setFocusableInTouchMode(true);

でparentにフォーカスを当てられる状態にしてからrequestFocus()を呼ぶことです。こうしなければparentにフォーカスが移動しないのでEditTextにフォーカスが残ったままになります。

また、onKeyPreImeの名のごとく、このメソッドはIMEが閉じるよりも前に呼ばれますので、superクラスのonKeyPreIme(int, KeyEvent)を呼んであげなければ、IMEは開いたままになります(InputMethodManagerを通して自分で閉じてやればいいですが)。

5
7
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
5
7