Default Focus and Keyboard to EditText in Android AlertDialog

前端 未结 5 1951
醉酒成梦
醉酒成梦 2021-02-12 09:24

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 th

5条回答
  •  孤街浪徒
    2021-02-12 09:54

    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:

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

    From the Android documentation on DialogFragments:

    If the user focuses on an EditText, the soft keyboard will automatically appear. In order to force this to happen with our programmatic focus, we call getDialog().getWindow().setSoftInputMode(). Note that many Window operations you might have done previously in a Dialog can still be done in a DialogFragment, but you have to call getDialog().getWindow() instead of just getWindow().

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
    
        //setup your dialog builder and inflate the view you want here
        ...
        //Make sure your EditText has the focus when the dialog is displayed
        edit.requestFocus();
        //Create the dialog and save to a variable, so we can set the keyboard state
        Dialog dialog = builder.create();
        //now, set to show the keyboard automatically
        dialog.getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        return dialog;
    }
    

提交回复
热议问题