1

I'm creating a dialog fragment using AlertDialog.Builder. I want it to just have a single EditText to grab some user text input. It works ok, but the IME keyboard does not pop up as soon as the dialog is shown. The EditText is already selected, but the user has to tap the EditText again to get the IME keyboard to pop up:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    EditText input = new EditText(getActivity());
    return new AlertDialog.Builder(getActivity())
        .setView(input)
        .create();
}

shouldn't it be popping up on its own immediately?

Thanks

user291701
  • 38,411
  • 72
  • 187
  • 285

2 Answers2

2

No, apparently it's not a default behaviour. If you really want keyboard to appear automatically, simulate a "tap" inside your EditText, here's what worked for me (this is safer than calling showSoftInput because of unreliable behavior of requestFocus, plus you don't need to micromanage the keyboard):

EditText tv = (EditText)findViewById(R.id.editText);
tv.post(new Runnable() {

            @Override
            public void run() {
                Log.d("RUN", "requesting focus in runnable");
                tv.requestFocusFromTouch();
                tv.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN , tv.getWidth(), tv.getHeight(), 0));
                tv.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP , tv.getWidth(), tv.getHeight(), 0));
            }
        });

I think the reason behind keyboard not opening up is that the user has to have a chance to see an entire window before deciding where to start editing first.

devmiles.com
  • 9,895
  • 5
  • 31
  • 47
  • It works for me. But the tap simulation looks not elegant to me. I finally found another solution from http://stackoverflow.com/a/8532417/94148 . The point is that requestFocus() need some time to take effect. – aleung Jan 13 '13 at 13:46
0

try this:

((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
    .showSoftInput(viewToEdit, 0);
dldnh
  • 8,923
  • 3
  • 40
  • 52