How to hide soft keyboard on android after clicking outside EditText?

前端 未结 30 1685
醉话见心
醉话见心 2020-11-22 11:46

Ok everyone knows that to hide a keyboard you need to implement:

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


        
相关标签:
30条回答
  • 2020-11-22 12:24

    There is a simpler approach, based on iPhone same issue. Simply override the background's layout on touch event, where the edit text is contained. Just use this code in the activity's OnCreate (login_fondo is the root layout):

        final LinearLayout llLogin = (LinearLayout)findViewById(R.id.login_fondo);
        llLogin.setOnTouchListener(
                new OnTouchListener()
                {
                    @Override
                    public boolean onTouch(View view, MotionEvent ev) {
                        InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(
                                android.content.Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(mActivity.getCurrentFocus().getWindowToken(), 0);
                        return false;
                    }
                });
    
    0 讨论(0)
  • 2020-11-22 12:24

    Just Add this code in the class @Overide

    public boolean dispatchTouchEvent(MotionEvent ev) {
        View view = getCurrentFocus();
        if (view != null && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) && view instanceof EditText && !view.getClass().getName().startsWith("android.webkit.")) {
            int scrcoords[] = new int[2];
            view.getLocationOnScreen(scrcoords);
            float x = ev.getRawX() + view.getLeft() - scrcoords[0];
            float y = ev.getRawY() + view.getTop() - scrcoords[1];
            if (x < view.getLeft() || x > view.getRight() || y < view.getTop() || y > view.getBottom())
                ((InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow((this.getWindow().getDecorView().getApplicationWindowToken()), 0);
        }
        return super.dispatchTouchEvent(ev);
    }
    
    0 讨论(0)
  • 2020-11-22 12:25

    I find the accepted answer bit complex for this simple requirement. Here's what worked for me without any glitch.

    findViewById(R.id.mainLayout).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                return false;
            }
        });
    
    0 讨论(0)
  • 2020-11-22 12:27

    You can achieve this by doing the following steps:

    1. Make the parent view(content view of your activity) clickable and focusable by adding the following attributes

          android:clickable="true" 
          android:focusableInTouchMode="true" 
      
    2. Implement a hideKeyboard() method

          public void hideKeyboard(View view) {
              InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
              inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
          }
      
    3. Lastly, set the onFocusChangeListener of your edittext.

          edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
              @Override
              public void onFocusChange(View v, boolean hasFocus) {
                  if (!hasFocus) {
                      hideKeyboard(v);
                  }
              }
          });
      

    As pointed out in one of the comments below, this might not work if the parent view is a ScrollView. For such case, the clickable and focusableInTouchMode may be added on the view directly under the ScrollView.

    0 讨论(0)
  • 2020-11-22 12:27

    Override public boolean dispatchTouchEvent(MotionEvent event) in any Activity (or extend class of Activity)

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        View view = getCurrentFocus();
        boolean ret = super.dispatchTouchEvent(event);
    
        if (view 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;
    }
    

    And that's all you need to do

    0 讨论(0)
  • 2020-11-22 12:28

    This may be old but I got this working by implenting a custom class

    public class DismissKeyboardListener implements OnClickListener {
    
        Activity mAct;
    
        public DismissKeyboardListener(Activity act) {
            this.mAct = act;
        }
    
        @Override
        public void onClick(View v) {
            if ( v instanceof ViewGroup ) {
                hideSoftKeyboard( this.mAct );
            }
        }       
    }
    
    public void hideSoftKeyboard(Activity activity) {
            InputMethodManager imm = (InputMethodManager)
            getSystemService(Activity.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
    }
    

    the best practice here is to create a Helper class and every container Relative / Linear Layouts should implement this.

    **** Take note only the main Container should implement this class (For optimization) ****

    and implement it like this :

    Parent.setOnClickListener( new DismissKeyboardListener(this) ); 
    

    the keyword this is for Activity. so if you are on fragment you use like getActivity();

    ---thumbs up if it help you... --- cheers Ralph ---

    0 讨论(0)
提交回复
热议问题