简体   繁体   English

在片段中隐藏键盘

[英]Hide keyboard from within a fragment

I try to hide the keyboard from within a fragment.我尝试在片段中隐藏键盘。 The fragment is inside a viewpager.该片段位于一个viewpager 中。

I use this code, which works fine when running on Android emulator.我使用此代码,在 Android 模拟器上运行时运行良好。

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

On a huawei mate 20 pro device view is always null .在 huawei mate 20 pro 设备上,视图始终为 null

How can I get this working on every device?我怎样才能让它在每台设备上都能正常工作?

I solved it by calling requestFocus() on the edittext before hiding the keyboard.我通过在隐藏键盘之前在 edittext 上调用requestFocus()来解决它。

getView().findViewById(R.id.notes_edittext).requestFocus();

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

Maybe its helpfull to someone else.也许它对其他人有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM