Displaying soft keyboard whenever AlertDialog.Builder object is opened

后端 未结 14 1802
半阙折子戏
半阙折子戏 2020-12-08 19:11

My code for opening an input dialog reads as follows:

final AlertDialog.Builder alert = new AlertDialog.Builder(this);  
alert.setTitle(\"Dialog Title\");  
         


        
14条回答
  •  佛祖请我去吃肉
    2020-12-08 19:58

    I know, this Question is really old, but since I've tried about 20 different so called 'solutions', I will post, what actually only worked for me finally.

    This answer is based on the answer of Pir Fahim Shah, who pointed me in the right direction (Thanks):

    Make sure, you put this in the onCreate of your activity, so that forced keyboards are being hidden, when dialog is closed:

    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    

    then create a dialog like this:

        AlertDialog.Builder builder = new Builder(this);
        builder.setTitle("title");
        final EditText input = new EditText(this);
        input.setText("text");
        input.setSelection(input.getText().length()); // set cursor to end
        builder.setView(input);
        input.setOnFocusChangeListener(new OnFocusChangeListener()  {
           public void onFocusChange(View v, boolean hasFocus) { 
               if(hasFocus) {
                   InputMethodManager inputMgr = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                   inputMgr.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_IMPLICIT_ONLY);
               }
           }
        });
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // do something here
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("Cancel", null);
        builder.show();
    

提交回复
热议问题