SoFunction
Updated on 2025-03-11

Android programming implements the function of hiding soft keyboard when clicking on controls other than EditText

This article describes the Android programming method that implements the function of hiding soft keyboards for clicking on controls other than EditText. Share it for your reference, as follows:

Tools

...
public static void hideKeyboard(Context ctx) {
    if (ctx != null) {
      View view = ((Activity) ctx).getCurrentFocus();
      if (view != null) {
        InputMethodManager inputManager = (InputMethodManager) ctx
            .getSystemService(Context.INPUT_METHOD_SERVICE);
        ((),
            InputMethodManager.HIDE_NOT_ALWAYS);
      }
    }
}

Click the control other than EDITTEXT to hide the soft keyboard. If it is a viewgroup control, execute it recursively.

public static void setupUI(View view, final Context ctx) {
    //Set up touch listener for non-text box views to hide keyboard.
    if(!(view instanceof EditText)) {
      (new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
          hideKeyboard(ctx);
          return false;
        }
      });
    }
    //If a layout container, iterate over children and seed recursion.
    if (view instanceof ViewGroup) {
      for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
        View innerView = ((ViewGroup) view).getChildAt(i);
        setupUI(innerView, ctx);
      }
    }
  }
...
}

When calling, you only need to pass the outermost layout.

((RelativeLayout) findViewById(.login_parent), mContext);

For more information about Android related content, please check out the topic of this site:Android control usage summary》、《Android development introduction and advanced tutorial》、《Android View View Tips Summary》、《Android programming activity operation skills summary》、《Android database operation skills summary"and"Android resource operation skills summary

I hope this article will be helpful to everyone's Android programming design.