SoFunction
Updated on 2025-03-11

Android click on locations other than editview to implement hidden input method

Android click on locations other than editview to implement hidden input method

Implementation code:

@Override 
  public boolean dispatchTouchEvent(MotionEvent ev) { 
    if (() == MotionEvent.ACTION_DOWN) { 
      View v = getActivity().getCurrentFocus(); 
      if (isShouldHideInput(v, ev)) { 
 
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); 
        if (imm != null) { 
          ((), 0); 
        } 
      } 
      return getActivity().dispatchTouchEvent(ev); 
    } 
    // Required, otherwise all components will not have TouchEvent    if (getActivity().getWindow().superDispatchTouchEvent(ev)) { 
      return true; 
    } 
    return getActivity().onTouchEvent(ev); 
  } 
 
  public boolean isShouldHideInput(View v, MotionEvent event) { 
    if (v != null && (v instanceof EditText)) { 
      int[] leftTop = { 0, 0 }; 
      //Get the current location of the input box      (leftTop); 
      int left = leftTop[0]; 
      int top = leftTop[1]; 
      int bottom = top + (); 
      int right = left + (); 
      if (() > left && () < right 
          && () > top && () < bottom) { 
        // Click the input box area, keep the event clicking EditText        return false; 
      } else { 
        return true; 
      } 
    } 
    return false; 
  } 

Thank you for reading, I hope it can help you. Thank you for your support for this site!