cain cain - 11 days ago 6
Android Question

Default Focus and Keyboard to EditText in Android AlertDialog

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();

Answer

Use the following code. It worked for me.

    editText.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            editText.post(new Runnable() {
                @Override
                public void run() {
                    InputMethodManager inputMethodManager= (InputMethodManager) YourActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
                }
            });
        }
    });
    editText.requestFocus();
Comments