點(diǎn)擊輸入框以外關(guān)閉鍵盤

在Activity中重寫下面這個(gè)方法:

@Override

public boolean dispatchTouchEvent(MotionEvent ev) {

if (ev.getAction() == MotionEvent.ACTION_DOWN) {

View v = getCurrentFocus();

? ? ? ? if (isShouldHideKeyboard(v, ev)) {

? ? ? ? ? hideKeyboard(v.getWindowToken(), this);

? ? ? ? }

}

return super.dispatchTouchEvent(ev);

}

根據(jù)EditText所在坐標(biāo)和用戶點(diǎn)擊的坐標(biāo)相對(duì)比,來(lái)判斷是否隱藏鍵盤,因?yàn)楫?dāng)用戶點(diǎn)擊EditText時(shí)則不能隱藏

public static boolean isShouldHideKeyboard(View v, MotionEvent event) {

if (v !=null && (vinstanceof EditText)) {

int[] l = {0, 0};

? ? ? ? v.getLocationInWindow(l);

? ? ? ? int left = l[0],

? ? ? ? ? ? ? ? top = l[1],

? ? ? ? ? ? ? ? bottom = top + v.getHeight(),

? ? ? ? ? ? ? ? right = left + v.getWidth();

? ? ? ? if (event.getX() > left && event.getX() < right

&& event.getY() > top && event.getY() < bottom) {

// 點(diǎn)擊EditText的事件,忽略它。

? ? ? ? ? ? return false;

? ? ? ? }else {

return true;

? ? ? ? }

}

// 如果焦點(diǎn)不是EditText則忽略,這個(gè)發(fā)生在視圖剛繪制完,第一個(gè)焦點(diǎn)不在EditText上,和用戶用軌跡球選擇其他的焦點(diǎn)

? ? return false;

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容