【问题标题】:How to show/hide the Android Soft Keyboard in dialog?如何在对话框中显示/隐藏 Android 软键盘?
【发布时间】:2019-09-07 00:35:22
【问题描述】:

在我的应用程序中,自定义对话框位于 BaseExpandableListAdapter 类中。 在对话框中,我有两个编辑文本。首先是名称及其强制性。其次是解决其可选问题。和两个按钮确定和取消。当对话框显示时,我想显示带有请求焦点的键盘以编辑文本名称。单击确定按钮后,软键盘应该会被隐藏。

【问题讨论】:

标签: android


【解决方案1】:

点击确定按钮,编写以下代码:-

  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。

【讨论】:

    【解决方案2】:
    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);  
       }
     }
    

    【讨论】:

      【解决方案3】:

      使用以下代码隐藏键盘

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

        希望对你有用

        【讨论】:

          【解决方案5】:

          这是一个解决方案:

              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)
              }
          
          

          【讨论】:

            【解决方案6】:

            在你的活动中使用它

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

            【讨论】:

            • 只要粘贴到你的活动课上就行了
            • 基本上是 ontouch 方法覆盖,我在其中放置了关闭软键盘的代码
            • 只需将其粘贴到您的活动类中,它是一个@Override 方法
            【解决方案7】:

            使用它。

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

            【讨论】:

              【解决方案8】:
              1. 当对话框显示时,我想显示具有编辑文本名称的请求焦点的键盘。

              这很容易,因为您自己已回答。在显示对话框之前,通过 xml 将 &lt;requestfocus/&gt; 添加到您的 EditText 或通过代码添加 editText.requestFocus();。

              1. 单击“确定”按钮后,软键盘应该会被隐藏。

              这可以通过两种方式实现,具体取决于您在单击“确定”按钮时所做的事情。

              一个。如果您正在开始一个新的 Activity - 在 Manifest 中将 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() 给出错误,然后将任何 View 传递给它(您可以通过 try catch 块跟踪它),其中 View 可以是任何东西、按钮、EditText 等您的活动 (myButton..getWindowToken())。

              【讨论】:

                【解决方案9】:

                显示Dialog时显示KeyBoard,按下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);
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2013-06-26
                  • 2016-10-22
                  • 2012-07-22
                  • 1970-01-01
                  • 2011-12-24
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多