android - 如何在 Android(Maybe Context)的外部类中调用 getCurrentFocus() 而不是 Activity

标签 android android-activity window

我想在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/

相关文章:

android - 如何更改 int 值 onclick 并将其传递给另一个 Activity ?在安卓上?

session - 是否可以让 gVim 记住窗口大小?

Jquery:如何检查新打开的窗口是否已完全加载?/window 加载外部页面(如 www.yahoo.com)

android - android中的痛苦线程

android - 如何在android中获取音乐文件(MP3)的采样率和频率?

java - 无法启动 Activity : Attempt to invoke virtual method (NullPointerException)

Android 常见的 Activity 和 FragmentActivity 父类(super class)

Python Tkinter 条目小部件不接受输入

android - 在 Jellybean 中,相机 Intent 在使用 FileProvider 时返回 RESULT.CANCELLED

android - 使用 SimpleCursorAdapter.ViewBinder 在 Listview 中更改文本颜色