问题描述
我想在 EditText
聚焦时自动显示软键盘(如果设备没有物理键盘),我有两个问题:
I want to automatically show the soft-keyboard when an EditText
is focused (if the device does not have a physical keyboard) and I have two problems:
当我的
Activity
显示时,我的EditText
被聚焦但没有显示键盘,我需要再次点击它以显示键盘(它应该在显示我的Activity
时显示).
When my
Activity
is displayed, myEditText
is focused but the keyboard is not displayed, I need to click again on it to show the keyboard (it should be displayed when myActivity
is displayed).
当我在键盘上点击完成时,键盘被关闭,但 EditText
保持聚焦并且你不想要(因为我的编辑已经完成).
And when I click done on the keyboard, the keyboard is dissmissed but the EditText
stays focused and y don't want (because my edit is done).
继续,我的问题是在 iPhone 上有一些更像的东西:它使键盘与我的 EditText
状态(聚焦/不聚焦)保持同步,当然不会出现软键盘如果有实体的话.
To resume, my problem is to have something more like on the iPhone: which keep the keyboard sync with my EditText
state (focused / not focused) and of course does not present a soft-keyboard if there is a physical one.
推荐答案
要强制出现软键盘,可以使用
To force the soft keyboard to appear, you can use
EditText yourEditText= (EditText) findViewById(R.id.yourEditText);
yourEditText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);
为了移除 EditText
上的焦点,遗憾的是你需要一个虚拟的 View
来获取焦点.
And for removing the focus on EditText
, sadly you need to have a dummy View
to grab focus.
要关闭它,您可以使用
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(yourEditText.getWindowToken(), 0);
这适用于在对话框中使用它
This works for using it in a dialog
public void showKeyboard(){
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
public void closeKeyboard(){
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
}
这篇关于如何在编辑文本聚焦时显示软键盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!