如何关闭/隐藏自定义Android键盘

4

我尝试在GridView中点击项目后关闭自定义键盘。我正在BaseAdapter类中尝试实现它。上下文是来自InputMethodService。

到目前为止,我尝试了以下方法:

FrameLayout scroll = (FrameLayout)inflater.inflate(R.layout.keyboard, null);
 InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(scroll.getWindowToken(), 0);

--

imm.toggleSoftInput(0,InputMethodManager.HIDE_IMPLICIT_ONLY);

--

 scroll.setVisibility(View.INVISIBLE);
3个回答

5
如果您有自己的自定义键盘,并且已经扩展了InputMethodService,那么您只需调用
requestHideSelf(0)

从您的服务中强制关闭键盘或

requestHideSelf(InputMethodManager.HIDE_IMPLICIT_ONLY);

仅当用户没有明确请求显示键盘时,才关闭键盘。

文档


2

我只是从我的应用程序中复制粘贴,这对我们来说很好用:

   public static void hideKeyboard(View v) {
      try {
         v.clearFocus();
         InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
         imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
      } catch (Exception e) {
         // we all saw shit happening on this code before
      }
   }

0
您可以将此方法放在公共类中,并在需要的地方调用它。
public static void hideKeyboard(Context ctx) {
InputMethodManager inputManager = (InputMethodManager) ctx
.getSystemService(Context.INPUT_METHOD_SERVICE);

// check if no view has focus:
 View v = ((Activity) ctx).getCurrentFocus();
 if (v == null)
    return;

inputManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
}

请参考我的回答这里


我遇到了“无法转换为Android.app.Activity”的错误,因为我的上下文类继承自InputMethodService :( 我无法使用activity(如果有方法我不知道)。 - Ömer Faruk Çakmakçı
如果你在一个键盘中,你可以通过requestHideSelf来隐藏自己。但是你的键盘可能没有gridView,所以我认为你有点困惑。 - Gabe Sechan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接