Android 點擊全鍵盤以外的區域隱藏軟鍵盤

一、重寫Activity的dispatchTouchEvent方法

@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        // Finger touch screen event
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            // get current focus,Generally it is EditText
            View view = getCurrentFocus();
            if (EditTextUtils.isShouldHideSoftKeyBoard(view, ev)) {
                EditTextUtils.hideSoftKeyBoard(view.getWindowToken(), DeviceBindActivity.this);
            }
        }
        return super.dispatchTouchEvent(ev);
    }

二、判斷工具類EditTextUtils

import android.content.Context;
import android.os.IBinder;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

public class EditTextUtils {

    /**
     * Judge what situation hide the soft keyboard,click EditText view should
     * show soft keyboard
     * 
     * @param v
     *            Incident event
     * @param event
     * @return
     */
    public static boolean isShouldHideSoftKeyBoard(View view, MotionEvent event) {
        if (view != null && (view instanceof EditText)) {
            int[] l = { 0, 0 };
            view.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + view.getHeight(), right = left + view.getWidth();
            if (event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom) {
                // If click the EditText event ,ignore it
                return false;
            } else {
                return true;
            }
        }
        // if the focus is EditText,ignore it;
        return false;
    }

    /**
     * hide soft keyboard
     * 
     * @param token
     */
    public static void hideSoftKeyBoard(IBinder token, Context context) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章