如何在Android(可能是Context)的外部类中调用getCurrentFocus()而不是activity

Mar*_*all 5 android window android-activity

我想从活动或片段中调用getCurrentFocus()以使结构看起来很漂亮.但是我怎样才能调用该方法?有时我使用context作为参数来实现类似的功能.

Nav*_*mad 23

您可以通过使用Activity,创建名为Utils的类并将以下代码放入其中来完成此操作.

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);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

现在您可以在任何Activity中调用此方法来隐藏键盘

Utils.hideKeyboard(Activity MainActivity.this);
Run Code Online (Sandbox Code Playgroud)