Android:当焦点在EditText上时自动显示软件键盘

我用AlertDialog显示了一个输入框。当我调用AlertDialog.show()时,对话框里的EditText自动获得焦点,但是软件键盘不会自动显示。
当对话框显示的时候我怎么做能够让软件键盘自动显示?(没有物理/硬件键盘)。和当我按下搜索按钮时调用全局搜索相似,软件键盘是自动显示的。

你可以在 AlertDialog的EditTex中创建一个焦点监听,然后获得AlertDialog的窗口。这样你就可以通过调用setSoftInputMode来显示软件键盘。

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

当创建了对话框之后你可以请求一个软件键盘

final AlertDialog dialog = ...; 
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

我也遇到了同样的问题,用下边的代码解决的。我不知道它在一个有本身键盘的手机上会显示成什么样子。

final EditText textEdit = new EditText(this);

AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Enter text");
alert.setView(textEdit);

alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        String text = textEdit.getText().toString();
        finish();
    }
});

alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        finish();
    }
});

AlertDialog dialog = alert.create();
dialog.setOnShowListener(new OnShowListener() {

    @Override
    public void onShow(DialogInterface dialog) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(textEdit, InputMethodManager.SHOW_IMPLICIT);
    }
});

dialog.show();