我想在EditText被聚焦时自动显示软键盘(如果设备没有物理键盘),我有两个问题:
当我的活动显示时,我的EditText是集中的,但键盘不显示,我需要再次单击它来显示键盘(它应该显示时,我的活动显示)。 当我在键盘上点击完成时,键盘被解散,但EditText保持集中,我不想(因为我的编辑已经完成)。
继续说,我的问题是有一些更像iPhone的东西:保持键盘与我的EditText状态同步(聚焦/不聚焦),当然,如果有物理键盘,也不会呈现软键盘。
我想在EditText被聚焦时自动显示软键盘(如果设备没有物理键盘),我有两个问题:
当我的活动显示时,我的EditText是集中的,但键盘不显示,我需要再次单击它来显示键盘(它应该显示时,我的活动显示)。 当我在键盘上点击完成时,键盘被解散,但EditText保持集中,我不想(因为我的编辑已经完成)。
继续说,我的问题是有一些更像iPhone的东西:保持键盘与我的EditText状态同步(聚焦/不聚焦),当然,如果有物理键盘,也不会呈现软键盘。
当前回答
在onCrete() activity()方法的editText上调用requestFocus()方法,并在相同的editText上调用clearFocus()方法,当在键盘上单击完成。
其他回答
void requestFocus(View editText, Activity activity)
{
try {
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) a.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
} catch (Exception e) {
e.printStackTrace();
}
}
加上这一行也不要忘记
activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
在onCrete() activity()方法的editText上调用requestFocus()方法,并在相同的editText上调用clearFocus()方法,当在键盘上单击完成。
要强制显示软键盘,可以使用
EditText yourEditText= (EditText) findViewById(R.id.yourEditText);
yourEditText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);
为了移除EditText上的焦点,你需要一个虚拟视图来抓取焦点。
关闭它,你可以使用
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(yourEditText.getWindowToken(), 0);
这适用于在对话框中使用它
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);
}
kotlin扩展使用下面。
fun EditText.toggle() {
requestFocus()
val imm = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(this, 0)
}
通过以下方式访问:
editText.toggle()
我把这里的所有东西结合起来,对我来说是有效的:
public static void showKeyboardWithFocus(View v, Activity a) {
try {
v.requestFocus();
InputMethodManager imm = (InputMethodManager) a.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
a.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
} catch (Exception e) {
e.printStackTrace();
}
}