Default Focus and Keyboard to EditText in Android AlertDialog
Asked Answered
P

7

27

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();
Purdy answered 21/3, 2012 at 20:23 Comment(0)
B
57

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();
Brok answered 24/10, 2012 at 19:23 Comment(3)
I tried so many methods before.. And this is the right one. Thank you very much, this code fits perfectly with AlertDialogGlanders
Sometimes it's working sometimes not. Approx. in 30 percent of showing dialog - keyboard is not appeared :(Carrousel
Regarding to the comment that sometimes work others not, if you put editText.postDelayed (theSameRunnable,100) it works 100% ;)Overstuff
B
22

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;
}
Buttock answered 17/4, 2014 at 18:50 Comment(4)
Way to go! This should be the accepted answer. I used getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); in my AppCompatDialog subclass's constructor.Nonie
dialog.getWindow() may return nullPomeroy
There is no such thing as LayoutParams.SOFT_INPUT_STATE_VISIBLE so this code can't compile.Harned
@Harned Here's the docs on that: developer.android.com/reference/android/view/… Perhaps you're missing an import for WindowManager? In either case it's possible this isn't necessary anymore when targeting >= P (API 9).Buttock
B
5

in your XML layout

call

<requestFocus/>

inside your default EditText

<EditText 
android:blabla
.... >
<requestFocus/>
</EditText>
Brocket answered 21/3, 2012 at 20:28 Comment(2)
The AlertDialog.Builder doesn't use an XML layout, it only takes in an EditText that was created in code. I've tried calling request focus on the generated EditText in multiple places, and it doesn't seem to work the way I would like it to. This is not a working solution for this question.Purdy
Using an XML in dialog.setView, this in combination with RightHandedMonkey's answer was the only way it worked for me.Longcloth
Q
1

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0); For hiding keyboard use:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(),0);

or try below code but you must set the requestFocus() or to your edittext

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);
        }
    }
});
Quinacrine answered 22/1, 2014 at 16:34 Comment(0)
S
1

use a custom view if you need it more often

public class RequestFocusEditText extends AppCompatEditText {
    private RequestFocusEditText self;

    public RequestFocusEditText(final Context context, AttributeSet attrs) {
        super(context, attrs);
        this.self = this;

        setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                post(new Runnable() {
                    @Override
                    public void run() {
                    InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.showSoftInput(self, InputMethodManager.SHOW_IMPLICIT);
                }
            });
        }
    });
    requestFocus();
    }
}
Sustainer answered 24/11, 2016 at 15:45 Comment(1)
Won't this show the keyboard when the edittext loses focus also. Doesn't seem correctEby
S
0

Well if the keyboard is not appearing even by editText.requestFocus() that means the window is not focused, make sure that the window is focused

Example for a dialog box, make sure you didn't add this flag to the dialog object, remove these lines if you have it

cdd.getWindow().
            setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);

and add this

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

and then editTextName.requestFocus(); will work well.

Sterlingsterlitamak answered 14/2, 2024 at 10:17 Comment(0)
C
0

I tried above all solutions but none of them worked for me. After reading a lot, finaly discovered the root cause of this, I realize that I don't need to use any workarounds (for me).

by default a dialog is in focusable mode and EditText were not getting focus, so i manually remove focus.

window?.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
Conn answered 6/3, 2024 at 12:3 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.