I am using the AlertDialog.Builder in Android to quickly prompt the user for text. The dialog shows up and works great, but the user must click on the EditText field to load the soft keyboard. Is there any way to open the keyboard and give focus to the whenever my dialog is opened? Here is my code:
final Map<String,Object> rowData = itemList.get(mPosition);
final EditText input = new EditText(searchList.getContext());
input.requestFocus();
input.setSingleLine();
final AlertDialog dialog = new AlertDialog.Builder(searchList.getContext())
.setTitle(StringUtils.getSafeString(rowData.get("label")))
.setView(input)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
rowData.put("value", StringUtils.getSafeString(input.getText()));
searchList.invalidateViews();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do nothing.
}
}).create();
dialog.show();
Hidden keyboard when programmatically setting focus on an EditText in an Android Dialog.
I had this problem as well and it was a pretty simple fix - here is my suggested solution. Although it worked on DialogFragments for me, I see no reason why it wouldn't work in your case.
Basically the soft keyboard isn't triggered because the view is being created programmatically. The actual fix was simply putting this line in the onCreateDialog method:
From the Android documentation on DialogFragments:
in your XML layout
call
inside your default EditText
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0); For hiding keyboard use:
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(),0);
or try below code but you must set the requestFocus() or to your edittext
Use the following code. It worked for me.
use a custom view if you need it more often