Android:在EditText上的自定义AlertDialog上显示软键盘Focus

Android:在EditText上的自定义AlertDialog上显示软键盘Focus

问题描述:

我有一个自定义的AlertDialog出现,但是当您点击布局中的EditText字段时,软键盘不会自动出现。我想这个解决方案Android: EditText in Dialog doesn't pull up soft keyboard使用:Android:在EditText上的自定义AlertDialog上显示软键盘Focus

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

那还不如我不把代码放在正确的位置一样简单。我在Activity的onCreateDialog和onPrepareDialog以及自定义AlertDialog的构造函数和onCreate中尝试了它。这没有用。

我更喜欢这种解决方案,因为这似乎是尝试为EditText字段设置onFocus侦听器的最佳实践。

如何我已经尝试过在活动

@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); 

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

+0

所以我假设AlertDialog禁止键盘,因为它只是提供一个消息和确定/取消按钮。它应该只是用作提示。 所以我只是将我的自定义对话框的基类更改为对话框。通过改变我的自定义Dialog继承的基类,EditText字段将在他们获得焦点时拉起软键/虚拟键盘,就像您期望的那样。 – mplspug 2012-02-19 00:40:39

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到对话框会导致错误的对话框位置我,所以我用这个方法。

+0

谢谢,帮我解决了! ^^ – animaonline 2013-01-30 16:34:33

+0

注意clearFlags只有在演出之后调用它才会起作用。 – Alexey 2013-04-09 14:38:25

+0

当我在'onStart'中使用它时很好地工作(在'show'之前使用它会导致NullPointerException异常) – hlt 2013-12-10 13:26:14