4

I have this piece of code (RelativeLayout is a just one row inside my main layout, not important).

RelativeLayout cellphoneNumberLayout = (RelativeLayout) findViewById(R.id.cellphone_number);
        cellphoneNumberLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SettingsDialog myDialog = new SettingsDialog(Main.this);
                myDialog.show();
            }
        });

Inside my custom Dialog (SettingsDialog) I have EditText and a Button. How can I force a keyboard to open immidiatelly when dialog is shown and focus on my (single) EditText field?

I tried with classic "forcing" which I found here on SO but this isn't activity, it's a dialog.

EDIT: I tried this but it's not working. Declared myDialog as class variable and added below myDialog.show();

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

Nothing happens.

svenkapudija
  • 5,128
  • 14
  • 68
  • 96

3 Answers3

6

The following will bring up the keyboard for the editText when it is focused:

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

Then just set editText to focused:

editText.setFocusable(true);
editText.requestFocus();
A. Abiri
  • 10,750
  • 4
  • 30
  • 31
  • It worked! I didn't need to manually set the focus in the editText as my dialog had a single field and was automatically focused by Android itself. – German Latorre Feb 14 '14 at 09:14
3

The following will bring up the keyboard for the editText when it is focused particularly when you have custom Dialog/DialogFragment:

myDialog.myEditTextField.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                }
            }
        });
Sameer Khader
  • 157
  • 1
  • 5
0

In AndroidManifest.xml, you can add android:windowSoftInputMode="stateVisible" to the activity tag to automatically show the keyboard.

NoBugs
  • 9,310
  • 13
  • 80
  • 146
  • 1
    Yeah, I could convert this into Activity, but I'm trying to find a way to do it without separate Activity, only with Dialog. – svenkapudija Jul 16 '11 at 19:35