Androidでedittext以外の部分をクリックしてソフトキーボードを隠す方法

2401 ワード

/**
 *        “  edittext           ”.
 *   HideKeyBoard.setupUI(**, **)
 *        findViewById(R.id.root_layout(  root_layout       id)
 *        activity   
 */
public class HideKeyBoard {
    public static void setupUI(View view, final Activity activity) {
        //      view   EditText。    ,      
        if (!(view instanceof EditText)) {
            view.setOnTouchListener(new OnTouchListener() {
                public boolean onTouch(View v, MotionEvent event) {
                    hideSoftKeyboard(activity); // Main.this   activity 
                    return false;
                }
            });
        }
        //     view,     view  
        if (view instanceof ViewGroup) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                View innerView = ((ViewGroup) view).getChildAt(i);
                setupUI(innerView, activity);
            }
        }
    }

    public static void hideSoftKeyboard(Activity activity) {
        InputMethodManager inputMethodManager = (InputMethodManager) activity
                .getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus()
                .getWindowToken(), 0);

    }
}

ツールクラスを定義し、上のコードcopyを参照してください.http://www.it165.net/pro/html/201405/13742.html