7

I want to call getCurrentFocus() out of activity or fragment to let the structure looks beautiful.But how can I call the method?Sometimes I use context as a parameter to achieve similar function.

Marshall
  • 1,961
  • 4
  • 14
  • 15

2 Answers2

25

You can do this by using Activity, Create a class named Utils and put the following code in it.

public class Utils{
public static void hideKeyboard(@NonNull Activity activity) {
    // Check if no view has focus:
    View view = activity.getCurrentFocus();
    if (view != null) {
        InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
  }
}

Now you can simply call this method in any Activity to hide keyboard

Utils.hideKeyboard(Activity MainActivity.this);
Naveed Ahmad
  • 6,199
  • 2
  • 54
  • 80
  • 1
    @Marshall Please Accept answer if it worked for you? People up-voted this answer so it means it is working. Thanks – Naveed Ahmad Jul 21 '16 at 07:49
  • 1
    `@NonNull` before the parameter would be a nice touch to prevent a call with a `null` activity which would throw a `NullPointerException` – Sunshinator Nov 08 '16 at 16:34
  • 1
    I just added the Null parameter check, Thanks for the suggestion, Appreciated – Naveed Ahmad Nov 11 '16 at 10:42
  • Is it possible to use it as not static method? I have activity instance in service object but I am not able to call activity.getCurrentFocus() – Čamo May 06 '20 at 12:00
0

You can use this:

fun Activity.hideKeyboard() {

    val view = currentFocus
    if (view != null) {
        val inputMethodManager =
            getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager

        inputMethodManager.hideSoftInputFromWindow(
            view.windowToken,
            InputMethodManager.HIDE_NOT_ALWAYS
        )
    }}
Ardent Coder
  • 3,309
  • 9
  • 18
  • 39
lhc777
  • 1
  • 2