問題描述
我的布局包含 ListView
、SurfaceView
和 EditText
.當我單擊 EditText
時,它會獲得焦點并彈出屏幕鍵盤.當我單擊 EditText
之外的某個位置時,它仍然具有焦點(它不應該).我想我可以在布局中的其他視圖上設置 OnTouchListener
并手動清除 EditText
的焦點.但似乎太 hackish...
My layout contains ListView
, SurfaceView
and EditText
. When I click on the EditText
, it receives focus and the on-screen keyboard pops up. When I click somewhere outside of the EditText
, it still has the focus (it shouldn't).
I guess I could set up OnTouchListener
's on the other views in layout and manually clear the EditText
's focus. But seems too hackish...
我在其他布局中也有相同的情況 - 具有不同類型項目的列表視圖,其中一些具有 EditText
的內部.他們的行為就像我上面寫的一樣.
I also have the same situation in the other layout - list view with different types of items, some of which have EditText
's inside. They act just like I wrote above.
任務是讓 EditText
在用戶觸摸外部的東西時失去焦點.
The task is to make EditText
lose focus when user touches something outside of it.
我在這里看到過類似的問題,但沒有找到任何解決方案...
I've seen similar questions here, but haven't found any solution...
推薦答案
我嘗試了所有這些解決方案.edc598 最接近工作狀態,但觸摸事件并未在布局中包含的其他 View
上觸發.如果有人需要這種行為,我最終會這樣做:
I tried all these solutions. edc598's was the closest to working, but touch events did not trigger on other View
s contained in the layout. In case anyone needs this behavior, this is what I ended up doing:
我創建了一個名為 touchInterceptor 的(不可見的)FrameLayout
作為布局中的最后一個 View
,以便它覆蓋所有內容(edit: 您還必須使用 RelativeLayout
作為父布局并賦予 touchInterceptor fill_parent
屬性).然后我用它來攔截觸摸并確定觸摸是否在 EditText
之上:
I created an (invisible) FrameLayout
called touchInterceptor as the last View
in the layout so that it overlays everything (edit: you also have to use a RelativeLayout
as the parent layout and give the touchInterceptor fill_parent
attributes). Then I used it to intercept touches and determine if the touch was on top of the EditText
or not:
FrameLayout touchInterceptor = (FrameLayout)findViewById(R.id.touchInterceptor);
touchInterceptor.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (mEditText.isFocused()) {
Rect outRect = new Rect();
mEditText.getGlobalVisibleRect(outRect);
if (!outRect.contains((int)event.getRawX(), (int)event.getRawY())) {
mEditText.clearFocus();
InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
}
return false;
}
});
返回 false 讓觸摸處理失敗.
Return false to let the touch handling fall through.
這很hacky,但它是唯一對我有用的東西.
It's hacky, but it's the only thing that worked for me.
這篇關于EditText,清晰專注于觸摸外的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!