Android: show soft keyboard automatically when focus is on an EditText
我读过这篇文章,在显示对话框时会自动显示虚拟键盘。但是,它不适合我。任何想法为什么?虽然当对话框出现时编辑文本自动聚焦,但事件不会触发。我也读过onpostresume的答案,但我不知道如何应用它。任何帮助表示赞赏。
final Dialog dialog = new Dialog(ThesisI.this);
dialog.setContentView(R.layout.budget_dialog);
final EditText et = (EditText) dialog.findViewById(R.id.textComments);
final Button enter = (Button) dialog.findViewById(R.id.buttonEnter);
final Button cancel = (Button) dialog.findViewById(R.id.buttonCancel);
enter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
/**cancel */
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
dialog.show();
et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
});
然而,我注意到如果我将焦点更改为按钮,则再次聚焦到编辑文本。此活动有效,请使用以下代码。
et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
InputMethodManager inputMgr = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMgr.toggleSoftInput(0, 0);
}
}
});
关于如何应用它的任何想法?
答案 0 :(得分:13)
您可以尝试将postDelayed(Runnable)
用于EditText,如下所示,
ettext.requestFocus();
ettext.postDelayed(new Runnable() {
@Override
public void run() {
InputMethodManager keyboard = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.showSoftInput(ettext, 0);
}
},200);
答案 1 :(得分:2)
尝试在"et.setOnFocusChangeListener"
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
.showSoftInput(et, 2);