EditText,清除重点在外面触摸
我的布局包含ListView
, SurfaceView
和EditText
。 当我点击EditText
,它会收到焦点并弹出屏幕上的键盘。 当我点击EditText
之外的某处时,它仍然有焦点(它不应该)。 我想我可以在布局中的其他视图上设置OnTouchListener
,并手动清除EditText
的焦点。 但似乎太恶心了...
我在其他布局列表视图中也有相同的情况,使用不同类型的项目,其中一些内部有EditText
。 他们的行为就像我上面写的。
任务是当用户触摸外部的东西时,使EditText
失去焦点。
我在这里看到过类似的问题,但还没有找到任何解决方案...
我试过所有这些解决方案。 edc598's最接近工作,但触摸事件不会在布局中包含的其他View
上触发。 如果有人需要这种行为,这就是我最终做的事情:
我创建了一个名为touchInterceptor的(不可见的) FrameLayout
作为布局中的最后一个View
,以便覆盖所有内容( 编辑:您还必须使用RelativeLayout
作为父布局,并赋予touchInterceptor fill_parent
属性)。 然后我用它来拦截触摸并确定触摸是否位于EditText
顶部:
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以使触摸处理完成。
这是hacky,但它是唯一对我有用的东西。
根据肯的回答,这是最模块化的复制和粘贴解决方案。
不需要XML。
将其放入您的活动中,并将应用于所有EditText,包括该活动中片段内的那些EditText。
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if ( v instanceof EditText) {
Rect outRect = new Rect();
v.getGlobalVisibleRect(outRect);
if (!outRect.contains((int)event.getRawX(), (int)event.getRawY())) {
v.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
}
return super.dispatchTouchEvent( event );
}
对于EditText的父视图,让以下3个属性为“ true ”:
可点击的 , 可调焦的 , 可调焦的触摸模式 。
如果一个视图想要获得焦点,它必须满足这三个条件。
请参阅android.view :
public boolean onTouchEvent(MotionEvent event) {
...
if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
...
if (isFocusable() && isFocusableInTouchMode()
&& !isFocused()) {
focusTaken = requestFocus();
}
...
}
...
}
希望能帮助到你。
链接地址: http://www.djcxy.com/p/24213.html