简体   繁体   中英

Android - Programmatically opening the keyboard/requesting focus on an EditText inside an AlertDialog

I have an Android Application and there's a part where I show an AlertDialog. In that AlertDialog, I have an EditText which is pre-populated with a value from the prefs and the user can change this.

The code works just fine, however, in order to be more intuitive with the User Experience, what I want to do is that when the Alert Dialog pops up, the pre-populated value from the preferences is highlighted already and the keyboard is ready.

So far, I have done the input highlight just fine but I can't get the keyboard to pop up or make the request focus work programmatically. Here's my code:

private void showPrefixChangerDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Set Pipe Prefix");

    final EditText input = new EditText(this);
    input.setInputType(InputType.TYPE_CLASS_NUMBER);
    input.setGravity(Gravity.CENTER_HORIZONTAL);
    input.setText(pipePrefix);
    input.setSelection(0, 2);
    input.performClick();
    input.requestFocus();
    InputFilter[] filters = new InputFilter[1];
    filters[0] = new InputFilter.LengthFilter(2);
    input.setFilters(filters);

    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(input, InputMethodManager.SHOW_IMPLICIT);


    builder.setView(input);

    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            String finalInput = input.getText().toString();
            saveInputToPrefs(finalInput);
            tv.setText("Pipe Prefix is " + finalInput);
        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });
    builder.show();
}

As you can see, I tried using performClick() , requestFocus() , and InputManager , but all to no avail.

Found the solution from this thread

    AlertDialog dialog = builder.create();
    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

    dialog.show();

I need to google better

Try this ("input" is your EditText):

InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.showSoftInput(input, 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