java - 以编程方式关闭键盘不适用于 Android 10

标签 java android android-softkeyboard android-10.0

我已经在我的 API 19 真实设备和 API 23 模拟器上测试过它,这个方法工作正常:

if(activity != null){
            View view = activity.getCurrentFocus();
            if (view != null){
                InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                if(inputManager != null){
                    inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
            }
        }

但是,它不适用于我的 Pixel 4a (android 10) 真实设备。有谁知道如何在 Android 10 上以编程方式关闭键盘?

最佳答案

根据您所在的位置,您可以使用以下方法之一:

boolean hideSuccess = KeyboardUtils.hideKeyboard(activity);

// or
boolean hideSuccess = KeyboardUtils.hideKeyboard(fragment);

// or
boolean hideSuccess = KeyboardUtils.hideKeyboard(editText); // It's recommended

KeyboardUtils.java

import android.app.Activity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import androidx.fragment.app.Fragment;

/**
 * @author aminography
 */
public class KeyboardUtils {

    public static boolean hideKeyboard(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        if (imm != null) {
            View focus = activity.getCurrentFocus();
            if (focus == null) focus = new View(activity);
            return imm.hideSoftInputFromWindow(focus.getWindowToken(), 0);
        } else {
            return false;
        }
    }

    public static boolean hideKeyboard(Fragment fragment) {
        InputMethodManager imm = (InputMethodManager) fragment.requireContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
        if (imm != null) {
            View focus = fragment.requireActivity().getCurrentFocus();
            if (focus == null) focus = new View(fragment.requireContext());
            return imm.hideSoftInputFromWindow(focus.getWindowToken(), 0);
        } else {
            return false;
        }
    }

    public static boolean hideKeyboard(EditText editText) {
        InputMethodManager imm = (InputMethodManager) editText.getContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
        if (imm != null) {
            return imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
        } else {
            return false;
        }
    }
}

关于java - 以编程方式关闭键盘不适用于 Android 10,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63966834/

相关文章:

java - 在 shell 脚本中解析 wmic 的输出

java - 使用 UrlEncode 在 Apachi Http Client 表单中正确编码百分号 (%)

java - FragmentManager 中的 NullPointerException

android - 如何动态减小 TextView 的大小

android - 如何在 Android 中向 KeyboardView 添加填充?

java - Scala 对象列表到逗号分隔的字符串

android - 添加 BulletSpan 时 EditText 不增加宽度

Android Webview 视频问题。视频正在 youtube iframe 中被裁剪。

android - 如何在StartTrackingTouch the seekbar上隐藏软键盘

android - 禁用键盘时 EditText 错误不会消失