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
  • 2,231
  • 4
  • 17
  • 15

3 Answers3

26

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,627
  • 2
  • 58
  • 83
  • 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,777
  • 9
  • 27
  • 53
lhc777
  • 1
  • 2
0

Extension function from a Fragment

fun Fragment.hideKeyboard() {
activity?.let {
    val view: View? = it.currentFocus
    if (view != null) {
        val imm =
            context!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
        imm!!.hideSoftInputFromWindow(view.windowToken, 0)
    }
}

}

Zain
  • 2,336
  • 1
  • 16
  • 25