Android: Dialog box show soft keyboard automatical

2019-01-20 12:05发布

问题:

Android: show soft keyboard automatically when focus is on an EditText

I've read this post that automatically shows the virtual keyboard when a dialog box is shown. however, it's not working for me. any ideas why? eventhough the edit text is automatically on focus when the dialogbox appear, the event doesn't trigger. I've also read the onpostresume answer but I don't know how to apply it. any help is appreciated.

final Dialog dialog = new Dialog(ThesisI.this);
        dialog.setContentView(R.layout.budget_dialog);


        final EditText et = (EditText) dialog.findViewById(R.id.textComments);
        final Button enter = (Button) dialog.findViewById(R.id.buttonEnter);
        final Button cancel = (Button) dialog.findViewById(R.id.buttonCancel);

        enter.setOnClickListener(new View.OnClickListener() {
      @Override
   public void onClick(View v) {

      }
        });
        /**cancel */
        cancel.setOnClickListener(new View.OnClickListener() {
      @Override
   public void onClick(View v) {
   }
        });       
        dialog.show(); 

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

                }
            }
        });

however, i noticed that if I change focus to the button then focus again to the edit text. this event works, using this code below.

et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                   InputMethodManager inputMgr = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                      inputMgr.toggleSoftInput(0, 0);
                }
            }
        });

any idea on how to apply it?

回答1:

What you can do is try using postDelayed(Runnable) for EditText as below,

                ettext.requestFocus();
                ettext.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        InputMethodManager keyboard = (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE);
                        keyboard.showSoftInput(ettext, 0);
                    }
                },200);


回答2:

Just try adding the below line before "et.setOnFocusChangeListener"

((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
                    .showSoftInput(et, 2);