当我在屏幕上单击编辑框的外部时,我想隐藏软键盘。我该怎么做呢?
发布于 2011-08-30 18:24:03
我必须编辑这个才能让它工作。添加了查看焦点视图是否为EditText的检查。
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
View v = getCurrentFocus();
boolean ret = super.dispatchTouchEvent(event);
if (v 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];
Log.d("Activity", "Touch event "+event.getRawX()+","+event.getRawY()+" "+x+","+y+" rect "+w.getLeft()+","+w.getTop()+","+w.getRight()+","+w.getBottom()+" coords "+scrcoords[0]+","+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;
}
也许可以用一种更流畅的方式来完成,但它真的工作得很好。
发布于 2012-08-09 13:39:22
这可以使用以下代码来完成:
1)使用findViewById()将父布局引用到java代码中。
2)然后对其应用setOnTouchListener()。
3)在onTouchMethod()中添加以下代码。
lin = (LinearLayout) findViewById(R.id.lin);
lin.setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
return false;
}
});
发布于 2011-06-20 22:10:32
我在我的活动中添加了以下内容。它之所以有效,是因为在可聚焦视图之外的触摸不会改变焦点(所以在== v中),但是触摸将在视图的矩形之外。
public boolean dispatchTouchEvent(MotionEvent event) {
View v = getCurrentFocus();
boolean ret = super.dispatchTouchEvent(event);
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];
Log.d("Activity", "Touch event "+event.getRawX()+","+event.getRawY()+" "+x+","+y+" rect "+w.getLeft()+","+w.getTop()+","+w.getRight()+","+w.getBottom()+" coords "+scrcoords[0]+","+scrcoords[1]);
if (event.getAction() == MotionEvent.ACTION_UP && (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w.getBottom()) ) {
inputManager.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
}
return ret;
}
编辑:修复小错误
https://stackoverflow.com/questions/4005728
复制相似问题