Android:当 EditText 获得焦点时在自定义 AlertDialog 中显示软键盘

3

我有一个自定义的AlertDialog弹出框,但是当你点击布局中的EditText字段时,软键盘不会自动弹出。我尝试了这个解决方案Android: EditText in Dialog doesn't pull up soft keyboard,使用以下代码:

dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

可能只是因为我没有将代码放在正确的位置。我已经尝试将其放在Activity的onCreateDialog和onPrepareDialog方法中,以及自定义AlertDialog的构造函数和onCreate方法中。但都没有成功。

我更喜欢这个解决方案,因为它似乎是最佳实践,而不是为EditText字段设置onFocus监听器。

以下是我在Activity中尝试使用该解决方案的方式:

@Override
protected Dialog onCreateDialog(int id) {
    Dialog dialog;
    switch (id) {
    case LOCATION_DETAILS_DIALOG:
        dialog = new LocationDetails(this, detailsSetListener);
        dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        return dialog;

    default:
        return null;
    }
}

protected void onPrepareDialog(final int id,final Dialog dialog){
    super.onPrepareDialog(id, dialog);
    switch (id) {
    case LOCATION_DETAILS_DIALOG:
       dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
    }
}

我曾在AlertDialog类中尝试过这种方法

public LocationDetails(Context context, DetailsSetEventListener detailsSetEventListener) {
    super(context);
    this.context = context;
    this.detailsSetEventListener = detailsSetEventListener;
    dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

有什么想法,为什么这不起作用?

所以我认为 AlertDialog 抑制了键盘,因为它只是提供消息和 OK/Cancel 按钮。 它应该仅用作提示。所以我刚刚将自定义对话框的基类更改为 Dialog。 通过更改自定义对话框继承的基类,EditText 字段将在获得焦点时弹出软件/虚拟键盘,就像您所期望的那样。 - mplspug
1个回答

10
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

对我来说很有效,我将其放在构造函数中,例如:

public CustomDialog(Context context) {
        super(context);
        show();
        setContentView(R.layout.widget_custom_dialog);

        getWindow().clearFlags(
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
    }

将 AlertDialog 更改为 Dialog 会导致对话框位置错误,因此我使用了这种方法。


谢谢,也帮助了我!^^ - animaonline
请注意,只有在调用show之后才能使用clearFlags。 - Alexey
当我在onStart中使用它时,它对我来说效果很好(如果在show之前使用它会导致空指针异常)。 - hlt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接