Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Show Soft Keyboard in Custom AlertDialog on EditText Focus

I have a custom AlertDialog come up, but when you tap on the EditText fields in the layout, the soft keyboard doesn't automatically come up. I tried this solution Android: EditText in Dialog doesn't pull up soft keyboard using:

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

It might be as simple as I am not putting the code in the correct location. I tried it in the onCreateDialog and onPrepareDialog of the Activity as well as the constructor and onCreate of the custom AlertDialog. That did not work.

I'd prefer this solution as this would seem best practices over trying to have a onFocus listener for the EditText fields.

How I've tried it in the Activity

@Override
protected Dialog onCreateDialog(int id) {
    Dialog dialog;
    switch (id) {
    case LOCATION_DETAILS_DIALOG:
        dialog = new LocationDetails(this, detailsSetListener);
        dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        return dialog;

    default:
        return null;
    }
}

protected void onPrepareDialog(final int id,final Dialog dialog){
    super.onPrepareDialog(id, dialog);
    switch (id) {
    case LOCATION_DETAILS_DIALOG:
       dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
    }
}

How I've tried it in the AlertDialog class

public LocationDetails(Context context, DetailsSetEventListener detailsSetEventListener) {
    super(context);
    this.context = context;
    this.detailsSetEventListener = detailsSetEventListener;
    dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

Any ideas why this does not work?

like image 637
mplspug Avatar asked Sep 08 '25 01:09

mplspug


1 Answers

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

works fine for me, I put it in the constructor, such as

public CustomDialog(Context context) {
        super(context);
        show();
        setContentView(R.layout.widget_custom_dialog);

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

Change AlertDialog to Dialog will cause the wrong dialog position for me, so I use this method.

like image 84
naive Avatar answered Sep 10 '25 05:09

naive