Android: Dialog box show soft keyboard automatical

2019-01-20 11:33发布

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?

2条回答
神经病院院长
2楼-- · 2019-01-20 12:06

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

((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
                    .showSoftInput(et, 2);
查看更多
The star\"
3楼-- · 2019-01-20 12:19

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);
查看更多
登录 后发表回答