Displaying soft keyboard whenever AlertDialog.Builder object is opened

This is in response to miannelle.

The following method is called when a menu option is selected:

private void addNote() {
    final Dialog dialog = new Dialog(this);
    dialog.setContentView(R.layout.textentryalertdialog);
    dialog.setTitle("Add note");
    TextView msgText = (TextView) dialog.findViewById(R.id.messagetext);
    msgText.setText("Whatever prompt you want");
    final EditText inputLine = (EditText) dialog.findViewById(R.id.my_edittext);
    Button okButton = (Button) dialog.findViewById(R.id.OKButton);
    okButton.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {
            dialog.dismiss();
            // app specific code
        }           
    });
    Button cancelButton = (Button) dialog.findViewById(R.id.CancelButton);
    cancelButton.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {
            dialog.dismiss();
        }           
    });
    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    dialog.show();
}

The textentryalertdialog.xml file defines a linear layout containing

TextView android:id="@+id/messagetext" ...

EditText android:id="@+id/my_edittext" ...

Button android:id="@+id/OKButton" ...

Button android:id="@+id/CancelButton" ...

I hope this helps.


As long as you always need to show the keyboard immediately once the dialog opens rather than once a specific form widget inside gets focus (for instance, if your dialog just shows an EditText and a button), you can do the following:

AlertDialog alertToShow = alert.create();
alertToShow.getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
alertToShow.show();

Rather than calling .show() on your builder immediately, you can instead call .create() which allows you to do some extra processing on it before you display it onto the screen.


try using view

v.getWindow().setSoftInputMode( 
           WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

With the encouragement of Mur Votema (see his answer above) I have answered my question by building a custom dialog based on the Dialog class. Unlike an alert based on AlertDialog.Builder such a custom dialog does accept the getWindow().setSoftInputMode(...) command and therefore allows the soft keyboard to be displayed automatically.

For guidance on building a custom dialog I found this web page and this especially helpful.