[英]Default Focus and Keyboard to EditText in Android AlertDialog
[英]Android - Programmatically opening the keyboard/requesting focus on an EditText inside an AlertDialog
我有一個Android應用程序,其中有一部分顯示了AlertDialog。 在該AlertDialog中,我有一個EditText,該文本預先填充了prefs中的值,用戶可以更改此值。
該代碼可以正常工作,但是,為了使用戶體驗更加直觀,我想做的是,當“警報對話框”彈出時,來自首選項的預填充值已經突出顯示,並且鍵盤已准備就緒。
到目前為止,我已經很好地完成了輸入突出顯示,但是我無法彈出鍵盤或使請求焦點以編程方式工作。 這是我的代碼:
private void showPrefixChangerDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Set Pipe Prefix");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setGravity(Gravity.CENTER_HORIZONTAL);
input.setText(pipePrefix);
input.setSelection(0, 2);
input.performClick();
input.requestFocus();
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter.LengthFilter(2);
input.setFilters(filters);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(input, InputMethodManager.SHOW_IMPLICIT);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String finalInput = input.getText().toString();
saveInputToPrefs(finalInput);
tv.setText("Pipe Prefix is " + finalInput);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
如您所見,我嘗試使用performClick()
, requestFocus()
和InputManager
,但都無濟於事。
從這個線程找到了解決方案
AlertDialog dialog = builder.create();
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
dialog.show();
我需要更好地谷歌
試試這個(“輸入”是您的EditText):
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.showSoftInput(input, InputMethodManager.SHOW_IMPLICIT);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.