简体   繁体   中英

Force show soft keyboard from within an AlertDialog

I have the following code which I think should work to force the keyboard to be shown when the Alert Dialog is shown.

public void showTypeBox(){
        edit = new EditText(this);
        edit.setPadding(10, 0, 0, 10);

        AlertDialog dialog = new AlertDialog.Builder(this)
            .setTitle("Type word to search for:")
            .setPositiveButton("Search", Main.this)
            .setNegativeButton("Cancel", null)
            .setView(edit)
            .setIcon(R.drawable.menu_icon)
            .create();
        dialog.show();

        InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        mgr.showSoftInput(edit, InputMethodManager.SHOW_IMPLICIT);
    }

I can't see what i'm doing wrong here.

You're trying to show the keyboard before the EditText is laid out and visible. Try this:

Handler delayedRun = new Handler();
delayedRun.post(new Runnable() {
  @Override
  public void run() {
    edit.requestFocus();
    InputMethodManager mgr = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    mgr.showSoftInput(addressBox, InputMethodManager.SHOW_IMPLICIT);
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM