Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call getCurrentFocus() in external class in Android(Maybe Context) instead of activity

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.

like image 997
Marshall Avatar asked Jul 12 '13 07:07

Marshall


1 Answers

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);
like image 129
Naveed Ahmad Avatar answered Nov 20 '22 00:11

Naveed Ahmad