1

I have a single edit text. I want that when the user is done with it, to clear it's focus.

Follwoinf all the answers here I've made the parent focusable and I clear the focus of my edit text when needed. The problem is that though it is not in focus anymore, the keyboard remains open because now the parent is in focus. For the user it makes no sense that the keyboard is still open.

**to be clear, I am using a method to dismiss the keyboard. It always works but doesn't work now, probably because what I've mentioned above.

Is there a way to remove focus AND close the keyboard?

This is the method I use to dismiss the keyboard.

fun closeKeyboard(activity: Activity) {

    val view = activity.currentFocus
    if (view != null) {
        val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
        imm!!.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_IMPLICIT_ONLY)
    }
}
Tsabary
  • 3,119
  • 2
  • 24
  • 66
  • 1
    This is not the same as the answer below: `InputMethodManager.HIDE_IMPLICIT_ONLY` is an enum whose value is 1, try passing 0 or `RESULT_UNCHANGED_SHOWN` – Martin Marconcini Jun 06 '19 at 16:47
  • Here is the discussion with some working solutions: https://stackoverflow.com/questions/15412943/hide-soft-keyboard-on-losing-focus – Alexey Ozerov Sep 24 '20 at 03:33

1 Answers1

0

Clear EditText Focus:

EditText editText = findViewById(R.id.someEditText);
editText.clearFocus();

or as last resort:

getWindow().getDecorView().clearFocus();

or also add these attributes to the layout:

android:focusable="true"
android:focusableInTouchMode="true"

Java from Activity

/*
 * Dismiss keyboard
 * */
try {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    View v = getWindow().getCurrentFocus();
    if (v != null) {
        IBinder windowToken = v.getWindowToken();
        if (windowToken != null && imm != null) {
            imm.hideSoftInputFromWindow(windowToken, 0);
        }
    }
} catch (Exception e) {
    System.out.println(e.getMessage());
}

Kotlin extension function

/*
 * Dismiss keyboard
 * */
 fun Context.dismissKeyboard() {
     val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
     val windowToken = (this as? Activity)?.currentFocus?.windowToken
     windowToken?.let { imm.hideSoftInputFromWindow(it, 0) }
 }
Rodrigo Queiroz
  • 2,674
  • 24
  • 30
  • It seems to be working on my AS emulator but not on my actual device. To be honest I am surprised it even work on my emulator as I've been dismissing the keyboard before as well with a slightly different function. I think the problem is that now a different view is in focus, but that view is just a container, so shouldn't have the keyboard. – Tsabary Jun 06 '19 at 02:30