我想在activity或fragment外调用getCurrentFocus(),让结构看起来很漂亮。但是我该如何调用该方法?有时我使用context作为参数来实现类似的功能。
最佳答案
您可以通过使用 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);
}
}
}
现在你可以简单地在任何Activity中调用这个方法来隐藏键盘
Utils.hideKeyboard(Activity MainActivity.this);
关于android - 如何在 Android(Maybe Context)的外部类中调用 getCurrentFocus() 而不是 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17609407/