Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when using AlertDialog.Builder with EditText, the Soft Keyboard doesn't pop

I've made such a thing

AlertDialog.Builder b = new AlertDialog.Builder(this);//....
AlertDialog dialog = b.create();

dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

dialog.show();

I've managed to solve it like this:

Dialog = builder.create();
Dialog.show();
Dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE  | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
Dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

I found out that the same code works properly on Tablet, the keyboard does pop up, but on Phone it doesn't, so researching further, seems to point to the "adjust" option.

I am using this, feels much cleaner.

AlertDialog d = builder.create();
d.getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
d.show();

In my case the only way I was able to show the keyboard when the Dialog was shown was by adding to my DialogFragment:

@Override
public void onResume() {
    super.onResume();
    getDialog().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
    getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    myEditText.requestFocus();
}

Note the SOFT_INPUT_STATE_ALWAYS_VISIBLE instead of SOFT_INPUT_STATE_VISIBLE.

From documentation:

// Visibility state for softInputMode: please always make the soft input 
// area visible when this window receives input focus.
int SOFT_INPUT_STATE_ALWAYS_VISIBLE;

When you call showDialog() to show a Dialog created using AlertDialog in onCreateDialog()

You should put the code in onPrepareDialog():

@Override
protected void onPrepareDialog (int id, Dialog dialog, Bundle args)
{
    TextView editText=(TextView) dialog.findViewById(R....);

    editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
       @Override
       public void onFocusChange(View v, boolean hasFocus) {
         if (hasFocus) {
            dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
         }
       }
    });
}

A much better solution is given here.

dialog.getWindow().clearFlags(
         WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
        |WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

No workaround. EditText behaves as expected.