Java tutorial
//package com.java2s; import android.content.Context; import android.graphics.Rect; import android.util.DisplayMetrics; import android.view.View; import android.view.inputmethod.InputMethodManager; public class Main { public static void hideSoftKeyboard(Context context, View view) { // Hide soft keyboard if keyboard is up if (isKeyboardShown(view.getRootView())) { InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); } } public static boolean isKeyboardShown(View rootView) { // 128dp = 32dp * 4, minimum button height 32dp and generic 4 rows soft keyboard final int SOFT_KEYBOARD_HEIGHT_DP_THRESHOLD = 128; Rect r = new Rect(); rootView.getWindowVisibleDisplayFrame(r); DisplayMetrics dm = rootView.getResources().getDisplayMetrics(); // heightDiff = rootView height - status bar height (r.top) - visible frame height (r.bottom - r.top) int heightDiff = rootView.getBottom() - r.bottom; // Threshold size: dp to pixels, multiply with display density boolean isKeyboardShown = heightDiff > SOFT_KEYBOARD_HEIGHT_DP_THRESHOLD * dm.density; // Log.d(TAG, "isKeyboardShown ? " + isKeyboardShown + ", heightDiff:" + heightDiff + ", density:" + dm.density // + "root view height:" + rootView.getHeight() + ", rect:" + r); return isKeyboardShown; } }