如何在对话框中显示/隐藏Android软键盘?

15

我的应用程序中,自定义对话框位于BaseExpandableListAdapter类中。在对话框中,我有两个编辑文本框。第一个是名称,必填项。第二个是地址,可选项。还有两个按钮:确定和取消。当对话框显示时,我想要显示键盘并聚焦于名称编辑文本框。点击“确定”按钮后,软键盘应该隐藏起来。


1
https://dev59.com/vHNA5IYBdhLWcg3wC5Xh?rq=1 - Sardor Dushamov
请访问以下链接:https://dev59.com/vHNA5IYBdhLWcg3wC5Xh?rq=1 - M D
展示你尝试过的内容以及哪些部分没有起作用。 - Sahil Mahajan Mj
最佳答案:https://dev59.com/A2Qo5IYBdhLWcg3wXuen#17393446 - Harpreet
9个回答

19
final Dialog dialog = new Dialog(_context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

dialog.setContentView(R.layout.prompts);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

final EditText name = (EditText) dialog.findViewById(R.id.name);
final EditText add = (EditText) dialog.findViewById(R.id.add);

Button btnok = (Button) dialog.findViewById(R.id.btn_ok);
Button btncancel = (Button) dialog.findViewById(R.id.btn_cancel);

 btnAddExpList.setOnClickListener(new OnClickListener() {
  @Override
   public void onClick(View v) {           dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);  
   }
 }

18

点击“确定”按钮后,请编写以下代码:

  final Dialog dialog=new Dialog(this);
    dialog.setContentView(R.layout.dialog);
    final EditText text = (EditText) dialog.findViewById(R.id.nameField);

   Button mOkBtn=(Button)dialog.findViewById(R.id.okBtn);


    // if button is clicked, close the custom dialog
   mOkBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            InputMethodManager imm = (InputMethodManager)getSystemService(context.INPUT_METHOD_SERVICE);
           imm.hideSoftInputFromWindow(text.getWindowToken(), 0);
        }
    });

    dialog.show();

将上下文定义为Context context=this。


5

使用以下代码隐藏键盘:

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

使用以下代码显示键盘
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

4
请使用这个函数:
public void hideKeyboard() {
    if (getDialog().getCurrentFocus() != null) {
        InputMethodManager inputManager = (InputMethodManager) Objects.requireNonNull(getActivity()).getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(getDialog().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
}

我希望它能够有用


2
这里提供一种解决方案:
    private fun showCustomDialog() {

        // Normal dialog stuff
        // -----
        val builder = AlertDialog.Builder(activity as Context) 
        val customLayout = View.inflate(context, R.layout.dialog_layout, null)
        val editText: EditText = customLayout.findViewById(R.id.edit_text)
        // -----

        // Get a hold of the inpoutMethodManager here
        val imm = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager

        builder.setTitle(getText(R.string.dialog_title))
        builder.setView(customLayout)
        builder.setPositiveButton(getText(R.string.action_confirm)) { _, _ ->
            // Hide the soft keyboard here after the positive button onclick
            imm.hideSoftInputFromWindow(editText.windowToken, 0)
            /*
             * Do your logic here for the positive click
             * ....
             */
        }
        builder.setNegativeButton(getText(R.string.action_cancel)) { dialog, _ ->
            // Also hide the soft keyboard if the user clicked negative button
            imm.hideSoftInputFromWindow(editText.windowToken, 0)
            /*
             * Do your logic here for the negative click
             * ....
             */
            dialog.cancel()
        }
        // added not cancelable for the dialog since it might mess with the keyboard hiding
        builder.setCancelable(false)
        builder.show()

        // make sure you call this to request focus, or else the hiding might not work...
        editText.requestFocus()
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)
    }


1
使用它。
protected void hideKeyboardDialog(Dialog dialog){
    View view = dialog.getView();
    if (view != null) {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}

1

Use this in your activity

@Override
    public boolean dispatchTouchEvent(MotionEvent event) {

        View v = getCurrentFocus();
        boolean ret = super.dispatchTouchEvent(event);

        if (v instanceof EditText) {
            View w = getCurrentFocus();
            int scrcoords[] = new int[2];
            w.getLocationOnScreen(scrcoords);
            float x = event.getRawX() + w.getLeft() - scrcoords[0];
            float y = event.getRawY() + w.getTop() - scrcoords[1];

            if (event.getAction() == MotionEvent.ACTION_UP && (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w.getBottom()) ) { 

                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
            }
        }
    return ret;
    }

只需将此内容复制粘贴到您的活动类中即可,伙计。 - Bhanu Sharma
基本上,这是ontouch方法重写,在其中我放置了用于关闭软键盘的代码。 - Bhanu Sharma
只需将其粘贴到您的活动类中,它是一个@ Override方法。 - Bhanu Sharma

0
在显示对话框时显示键盘,并在按下“确定”按钮时关闭键盘,如下所示:

显示KeyBoard时显示Dialog,并在按下OK按钮时关闭KeyBoard...

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getApplicationContext());
alertDialogBuilder.setTitle(getString(R.string.app_error) + ":" + errorCode);
alertDialogBuilder.setMessage("Message");
alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

      @Override
      public void onClick(DialogInterface dialog, int id) {

          imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);       }
});

alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

      @Override
      public void onClick(DialogInterface dialog, int id) {

      }
});

AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();

imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

0
  1. 当 Dialog 弹出时,我想为编辑文本名称显示请求焦点的键盘。

这很容易,如你自己所回答的。在显示对话框之前,通过 XML 或代码添加 <requestfocus/> 到您的 EditText 中,即可实现 editText.requestFocus();

  1. 单击 OK 按钮后,软键盘应该隐藏。

这可以通过两种方式实现,取决于您单击 OK 按钮时要执行什么操作。

a. 如果您要启动新的 Activity - 在清单中将 android:windowSoftInputMode="stateHidden" 添加到此 Activity 中,因此每次启动 Activity 时都会隐藏键盘,除非您调用它。

b. 如果您在同一页上 - 调用下面的方法。

    private void hideSoftKeyBoard() {
            try {
                // hides the soft keyboard when the drawer opens
                InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

                inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

如果getCurrentFocus().getWindowToken()出错,则将任何视图传递给它(您可以通过try catch块跟踪此操作),其中视图可以是您的Activity中的任何内容,例如Button、EditText等(myButton..getWindowToken())。


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