当我显示带有 EditText 的对话框时,如何使软键盘出现?
我在这里读了几篇文章,也尝试过谷歌搜索。但我仍然遇到这个问题:
我制作了一个子类化的自定义对话框。它包含一个 EditText 和一个按钮(“确定”)。我想让键盘在弹出对话框后自动显示。
我成功地做到了这一点,将其放入
imm = (InputMethodManager) EditDialog.this.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_NOT_ALWAYS);
自定义对话框的 onCreate() 和
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
dismiss() 中。
一旦弹出对话框,就会打开键盘,并且在按下“确定”按钮后也会关闭键盘。
但是,如果软键盘打开并且我按下手机/模拟器的主页按钮,它们的键盘将保持打开状态,因为 - 我想 - 我用 SHOW_FORCED 强制它打开。因此,如果键盘在对话框的父活动 onPause() 方法中打开,我尝试隐藏(使用 InputMethodManager 中的toggleSoftInput())键盘。这似乎只能使用解决方法来实现,如此处所示。
TL;DR:我希望在弹出带有 EditText 和按钮的对话框时显示软键盘(重点关注 EditText)。我已经做到了,但它涉及编写许多技巧来正确关闭它。
编辑:我的代码基于 这个
I read a couple of the posts here and also tried googling. But I still have this problem:
I have made a subclassed custom Dialog. It contains an EditText and a Button ("OK"). I want to have the keyboard show automatically once the dialog pops up.
I succeeded doing so by putting this:
imm = (InputMethodManager) EditDialog.this.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_NOT_ALWAYS);
in my onCreate() of the custom dialog and
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
in my dismiss().
This opens the keyboards once the dialog pops up and also closes the keyboard once I press the "OK" button.
However, if the Soft Keyboard is open and I press the HOME Button of my phone/the emulator, they keyboard will stay open, since - I figured - I force it open with SHOW_FORCED. I thus tried to hide (using toggleSoftInput() from InputMethodManager) the keyboard if it is open in the dialog's parent activity onPause() method. this seems only to be possible using a workaround, as seen HERE.
TL;DR: I want the Soft Keyboard to be shown when my Dialog with an EditText and a Button pops up (focus on EditText). I got that working but it involved writing many hacks to close it properly.
Edit: I based my code on THIS
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
以及 EditTextView 类型的“视图”。 “上下文”是当前上下文。
希望可以帮到你。
And "view" of type EditTextView. "context" is current Context.
Wish can help u.
您可以使用此 KeyboardHelper.java 类来显示和隐藏键盘
You can use this KeyboardHelper.java class to show and hide the keyboard
此处回答了这个< /a>,这对我来说非常有用。如果我在显示键盘时按主页按钮,则按主页键后它会正确隐藏。
This was answered here, and it works great for me. If I press the home button while the keyboard is displayed, it correctly hides after pressing the home key.