Android 如何避免单击按钮时调用dispatchTouchEvent
在我的活动中,我有一个Android 如何避免单击按钮时调用dispatchTouchEvent,android,android-softkeyboard,android-button,touch-event,Android,Android Softkeyboard,Android Button,Touch Event,在我的活动中,我有一个编辑文本和一个按钮。我覆盖了dispatchTouchEvent以在单击屏幕上除EditText以外的其他区域时隐藏软键盘 @Override public boolean dispatchTouchEvent(MotionEvent event) { View view = getCurrentFocus(); boolean ret = super.dispatchTouchEvent(event); if (view instanceof E
编辑文本
和一个按钮
。我覆盖了dispatchTouchEvent
以在单击屏幕上除EditText
以外的其他区域时隐藏软键盘
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
View view = getCurrentFocus();
boolean ret = super.dispatchTouchEvent(event);
if (view instanceof EditText) {
View w = getCurrentFocus();
int scrcoords[] = new int[2];
w.getLocationOnScreen(scrcoords);
float x = event.getRawX() + w.getLeft() - scrcoords[0];
float y = event.getRawY() + w.getTop() - scrcoords[1];
if (event.getAction() == MotionEvent.ACTION_UP
&& (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w
.getBottom())) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getCurrentFocus()
.getWindowToken(), 0);
}
}
return ret;
}
@覆盖
公共布尔dispatchTouchEvent(MotionEvent){
视图=getCurrentFocus();
布尔ret=super.dispatchTouchEvent(事件);
如果(查看EditText的实例){
视图w=getCurrentFocus();
int scrcoords[]=新int[2];
w、 getLocationOnScreen(scrcoords);
float x=event.getRawX()+w.getLeft()-scrcoords[0];
float y=event.getRawY()+w.getTop()-scrcoords[1];
如果(event.getAction()==MotionEvent.ACTION\u UP
&&(x=w.getRight()| | yw
.getBottom()){
InputMethodManager imm=(InputMethodManager)getSystemService(Context.INPUT\u方法\u服务);
imm.hideSoftInputFromWindow(getWindow().getCurrentFocus())
.getWindowToken(),0);
}
}
返回ret;
}
问题是,每次我单击按钮
,都会调用dispatchTouchEvent
,因此软键盘将消失,这不是我想要的。我不想在单击按钮时隐藏键盘。我想的是,当我单击按钮时,是否可以避免调用dispatchTouchEvent
任何反馈都将不胜感激。您无需覆盖dispatchTouch事件。只需将活动的onClickListener设置为与按钮和EditText相同,然后调用方法以隐藏交换机外壳的“默认”外壳上的软键盘
switch (v.getId())
{
case R.id.button:
whateverButtonDoes();
break;
case R.id.editText:
whateverEditTextDoes();
break;
default:
hideKeyboard();
break;
}
我强烈建议您定义一种隐藏键盘的方法,以实现清晰的编码标准。您也可以在其他地方使用它。添加逻辑来检测按钮的坐标。
是否也可以?或者,如果版面的其余部分不是交互式的,您可以只在主版面上单击一个侦听器来执行此操作。dispatchTouchEvent中的v.getid()与我的按钮R.id.button不同。您能告诉我为什么会发生这种情况吗??