35

我打开输入对话框的代码如下:

final AlertDialog.Builder alert = new AlertDialog.Builder(this);  
alert.setTitle("Dialog Title");  
alert.setMessage("Request information");  
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.edittextautotextlayout, null);
final EditText inputBox = (EditText) textEntryView.findViewById(R.id.my_et_layout);
alert.setView(inputBox);

这很好用,只是我必须在软键盘出现之前点击文本输入行。

按照此处给出的建议,我尝试插入:

inputBox.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            alert.getWindow().setSoftInputMode( 
               WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }
});

但是 Eclipse 对象“方法 getWindow() 没有为 AlertDialog.Builder 类型定义”。

似乎 setOnFocusChangeListener 代码适用于 AlertDialog 对象,但不适用于 AlertDialog.Builder。我应该如何修改我的代码以使软键盘自动出现。

4

14 回答 14

83

只要您总是需要在对话框打开后立即显示键盘,而不是在内部的特定表单小部件获得焦点(例如,如果您的对话框只显示一个EditText和一个按钮),您可以执行以下操作:

AlertDialog alertToShow = alert.create();
alertToShow.getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
alertToShow.show();

而不是.show()立即调用您的构建器,您可以改为调用.create()which 允许您在将其显示到屏幕上之前对其进行一些额外的处理。

于 2011-05-25T11:44:16.723 回答
16

这是对 miannelle 的回应。

选择菜单选项时调用以下方法:

private void addNote() {
    final Dialog dialog = new Dialog(this);
    dialog.setContentView(R.layout.textentryalertdialog);
    dialog.setTitle("Add note");
    TextView msgText = (TextView) dialog.findViewById(R.id.messagetext);
    msgText.setText("Whatever prompt you want");
    final EditText inputLine = (EditText) dialog.findViewById(R.id.my_edittext);
    Button okButton = (Button) dialog.findViewById(R.id.OKButton);
    okButton.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {
            dialog.dismiss();
            // app specific code
        }           
    });
    Button cancelButton = (Button) dialog.findViewById(R.id.CancelButton);
    cancelButton.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {
            dialog.dismiss();
        }           
    });
    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    dialog.show();
}

textentryalertdialog.xml 文件定义了一个线性布局,其中包含

TextView android:id="@+id/messagetext" ...

EditText android:id="@+id/my_edittext" ...

按钮 android:id="@+id/OKButton" ...

按钮 android:id="@+id/CancelButton" ...

我希望这有帮助。

于 2011-01-28T08:50:56.847 回答
7

在 Mur Votema 的鼓励下(见上面他的回答),我通过构建一个基于 Dialog 类的自定义对话框来回答我的问题。与基于 AlertDialog.Builder 的警报不同,这样的自定义对话框确实接受 getWindow().setSoftInputMode(...) 命令,因此允许自动显示软键盘。

有关构建自定义对话框的指导,我发现这个网页特别有用。

于 2010-11-06T21:05:16.990 回答
2

尝试使用视图

v.getWindow().setSoftInputMode( 
           WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
于 2010-10-30T14:20:12.030 回答
2

您是否尝试将焦点放在您的 EditText -> inputBox.requestFocus() 或类似的东西上?

于 2010-10-30T14:33:13.240 回答
2

如果您想与软键盘一起弹出对话框,以便用户可以免于点击对话框内的编辑文本以显示键盘,例如,如果您要从对话框中获取一些值,那么使用这个简单的代码,它会解决你的问题。

        public void onClick(final View v) 
        {   
             AlertDialog.Builder alert = new AlertDialog.Builder(v.getContext());                 
              alert.setIcon(R.drawable.smsicon);
              alert.setTitle(" Secrete Code");  
              alert.setMessage("Enter a Key for secrete text !");
              final EditText shft_val = new EditText(v.getContext()); 
              shft_val.setInputType(InputType.TYPE_CLASS_NUMBER);//changing the keyBoard to No only,restrict the string etc
              alert.setView(shft_val);

     //pOp Up the key pad on Edit Text  focus event

             shft_val.setOnFocusChangeListener(new OnFocusChangeListener()
             {
                public void onFocusChange(View arg0, boolean arg1)
                {  InputMethodManager inputMgr = (InputMethodManager)v.getContext().
                                    getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMgr.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_IMPLICIT_ONLY);
                        }
                    });

                 alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() 
                 {  
                 public void onClick(DialogInterface dialog, int whichButton) 
                 {
                    //Your specific code... 
                 }
                 });
                 alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

                     public void onClick(DialogInterface dialog, int which) {                       
                         dialog.dismiss();
                         return;   
                     }
                 });
                       alert.show();
                    }
于 2012-12-09T18:26:10.287 回答
1

尝试使用inputBox

inputBox.getWindow().setSoftInputMode( 
               WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
于 2010-10-29T18:43:25.410 回答
1

我认为您几乎可以在原始问题中使用它。尝试创建一个final AlertDialog调用getWindow(),例如

// Create the dialog used to modify the mailbox alias
final AlertDialog dialog = alert.create();

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

我已经测试了这段代码,现在键盘会自动出现在我的大多数设备上,包括:

  • 三星 Galaxy Tab 操作系统 2.2
  • 三星 Galaxy S 操作系统 2.1
  • HTC 感觉操作系统 2.3.4

关于此解决方案的其他一些评论:

1)检查您的 XML 中是否已经有任何东西来请求焦点,因为这可能会阻止此代码工作(根据您链接到的问题中的 Ted)。

2) 此代码似乎不适用于运行 OS 2.3.4 的 HTC G2。我想这是因为它有一个物理键盘,也许该WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE选项不适用于它?

我还尝试了 SOFT_INPUT_STATE_VISIBLE(没有 ALWAYS),但这会阻止键盘自动出现。

3)您可能还想添加代码,以便用户可以按键盘上的完成按钮来提交更改,例如

inputAlias.setOnKeyListener(new OnKeyListener()
{
  @Override
  public boolean onKey(View v, int keyCode, KeyEvent event)
  {
    if (keyCode == KeyEvent.KEYCODE_ENTER &&
        inputAlias.isFocused() &&
        inputAlias.getText().length() != 0)
    {
      // Save the new information here

  // Dismiss the dialog
      dialog.dismiss();
      return true;
    }
    return false;
  }
});
于 2011-10-23T18:30:34.180 回答
1

我知道,这个问题真的很老了,但是由于我已经尝试了大约 20 种不同的所谓“解决方案”,所以我会发布,实际上最终只对我有用。

这个答案基于 Pir Fahim Shah 的回答,他为我指明了正确的方向(谢谢):

确保将其放在活动的 onCreate 中,以便在关闭对话框时隐藏强制键盘:

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

然后创建一个这样的对话框:

    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();
于 2014-12-10T21:45:37.053 回答
1

我创建AlertDialog并使用了一个自定义视图,其中包含一个EditText. 我希望在显示对话框时显示软键盘,并且无论用户单击“确定”按钮还是在对话框之外的某个位置都隐藏软键盘。

这段代码来自androidx.perference.PreferenceDialogFragmentCompat我整理了一下。

final AlertDialog.Builder builder = new AlertDialog.Builder(context)
        .setTitle(mDialogTitle)
        .setPositiveButton(mPositiveButtonText, null)
        .setNegativeButton(mNegativeButtonText, null);

View contentView = LayoutInflater.from(context).inflate(resId, null);

mEditText = contentView.findViewById(android.R.id.edit);

/**
 * From PreferenceDialogFragmentCompat.needInputMethod
 * <p>Note: If your application targets P or above, ensure your subclass manually requests
 * focus (ideally in {@link #onBindDialogView(View)}) for the input field in order to
 * correctly attach the input method to the field.
 */
mEditText.requestFocus();

builder.setView(contentView);

final Dialog dialog = builder.create();
dialog.window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

// This is not from PreferenceDialogFragmentCompat and I add it.
// It seems the soft keyboard won't get dismissed on some old devices without this line.
dialog.setOnDismissListener {
    dialog.window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}

dialog.show();

您无需修改​​ Manifest。EditText无论您单击对话框操作按钮还是对话框外的某个位置,它都会自动聚焦并被关闭。

于 2019-04-14T02:33:11.320 回答
0

嗨 Prepbgg 实际上有另一种方法可以替代您所做的事情。我实际上不得不在我的 ArrayAdapter 中使用我的。我所做的是将活动的上下文传递到 arrayadapter,然后调用它来访问 getWindow() ,如下所示:

NoteArrayAdapter(Activity _activity, int _layout, ArrayList<Note> _notes, Context _context) {
  callingNoteListObj = (NoteList) _context;
}

// withiin getView

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

// within parent activity's onCreate()
thisObject = this;

//within my parent activity's fillData() (NoteList)
adapter =  new NoteArrayAdapter(activity, R.layout.channel_note_list_item, noteList, thisObject);
于 2011-09-09T04:47:44.393 回答
0

在下面的代码片段中,我展示了如何LinearLayoutDialogFragment. 一种使用AlertDialog(软键盘不起作用)和另一种不使用AlertDialog(软键盘起作用!):

public static LinearLayout createLinearLayout(Context context)
{
    LinearLayout linearLayout = new LinearLayout(context);
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    linearLayout.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    String html;
    html = "<form action=search method=get >\n";
    html += "Google Search: <input name=q value=\"Johnny Depp\" /><br/>\n";
    html += "<input type=submit name=output value=search /><br/>\n";
    html += "</form>\n";
    WebView webView = new WebView(context);
    webView.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebChromeClient(new WebChromeClient());
    webView.setWebViewClient(new WebViewClient());
    webView.loadDataWithBaseURL("http://www.google.com", html, "text/html", "UTF-8", null);
    linearLayout.addView(webView);
    return linearLayout;
}

public void showWithAlertDialog()
{
    DialogFragment dialogFragment = new DialogFragment()
    {
        public Dialog onCreateDialog(Bundle savedInstanceState)
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder
                .setTitle("With AlertDialog")
                .setView(createLinearLayout(getActivity()));
            return builder.create();
        }
    };
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    dialogFragment.show(fragmentTransaction, "dialog");
}

public void showWithoutAlertDialog()
{
    DialogFragment dialogFragment = new DialogFragment()
    {
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            getDialog().setTitle("Without AlertDialog");
            getDialog().setCanceledOnTouchOutside(false);
            return createLinearLayout(getActivity());
        }
    };
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    dialogFragment.show(fragmentTransaction, "dialog");
}
于 2012-11-29T23:46:18.957 回答
0

我发现这在从不同地方调用的警报对话框中有效

        case R.id.birthyear:
        case R.id.ymax:
            input.setInputType(InputType.TYPE_CLASS_NUMBER);
            break;

请注意,我也尝试了很多其他的东西。显得细腻。

于 2016-02-02T12:54:10.053 回答
0

.setView()将在对话框中自动调出键盘。请注意 EditText 本身的“最终”。重要的!

AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Random Title...");
alert.setMessage("Type a name");

final EditText input = new EditText(this);

//Set input focus (which opens the android  soft keyboard)
alert.setView(input);   
input.setHint("My Name is...");
//Set keyboard type
input.setInputType(InputType.TYPE_CLASS_TEXT); 

//add button onclick handlers...

alert.show();

我认为很多人真的过度使用所有功能......这是相当普遍的并且工作得很好。而且它不会使您的代码膨胀。

于 2018-10-13T04:43:23.873 回答