EditText 和軟鍵盤常見用法
前因
產(chǎn)品有這樣一個(gè)需求,一個(gè)輸入框句喷,剛開始進(jìn)入頁面的時(shí)候不獲取焦點(diǎn),第一次點(diǎn)擊輸入框光標(biāo)到最后酬诀,后面再點(diǎn)擊定位到具體文字脏嚷,鍵盤收起來輸入框失去焦點(diǎn)骆撇。
分析與實(shí)現(xiàn)
其實(shí)即使把 EditText
的使用方式組合起來瞒御,再監(jiān)聽一下軟鍵盤的抬起,其中的一些小細(xì)節(jié)還是需要考慮的神郊。
-
功能一:
EditText
剛進(jìn)入見面的時(shí)候不獲取焦點(diǎn)肴裙,不自動(dòng)彈出鍵盤解決:在父布局 加上下面兩個(gè)屬性,獲取焦點(diǎn)即可:
android:focusable="true" android:focusableInTouchMode="true"
-
功能二:第一次點(diǎn)擊后光標(biāo)到最后涌乳,再點(diǎn)擊定位到具體文字
這個(gè)稍微麻煩一點(diǎn)蜻懦,首先關(guān)閉
EditText
的焦點(diǎn):android:focusable="false"
然后監(jiān)聽
EditText
的點(diǎn)擊事件:etLeaveWords.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!etLeaveWords.hasFocus()) { etLeaveWords.setFocusable(true); etLeaveWords.setFocusableInTouchMode(true); etLeaveWords.requestFocus(); KeyboardUtil.softShow(mContext, etLeaveWords); String message = etLeaveWords.getText().toString(); if (!TextUtils.isEmpty(message)) { etLeaveWords.setSelection(message.length()); } } } });
注意這幾部是一個(gè)整體,因?yàn)?requestFocus() 后用戶需要再點(diǎn)擊一次才可以顯示鍵盤夕晓,這里我們直接強(qiáng)行顯示出來:
etLeaveWords.setFocusable(true); etLeaveWords.setFocusableInTouchMode(true); etLeaveWords.requestFocus(); KeyboardUtil.softShow(mContext, etLeaveWords); // 顯示鍵盤
至于定位宛乃,直接調(diào)用
setSelection()
方法至于軟件盤消失,
EditText
失去焦點(diǎn)蒸辆,用的網(wǎng)上的一個(gè)方案:etLeaveWords.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { Rect r = new Rect(); etLeaveWords.getWindowVisibleDisplayFrame(r); int heightDiff = etLeaveWords.getRootView().getHeight() - (r.bottom - r.top); if (heightDiff < 200) { // 處理鍵盤隱藏 etLeaveWords.setFocusable(false); } } });