小智 58
不得不编辑这个以使其工作.添加了一个检查以查看焦点视图是否为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;
}
Run Code Online (Sandbox Code Playgroud)
可能会以更顺畅的方式完成,但它的效果非常好.
Nic*_*ely 32
要强制隐藏键盘,您可以使用以下代码...我将它放在一个名为'hideSoftKeyboard()'的方法中.正如Falmarri所提到的,当你点击它时,软键盘应该隐藏起来.但是,如果您在另一个项目的"onClick()"中调用此方法,它将强制关闭键盘.
private void hideSoftKeyboard(){
if(getCurrentFocus()!=null && getCurrentFocus() instanceof EditText){
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(yourEditTextHere.getWindowToken(), 0);
}
}
Run Code Online (Sandbox Code Playgroud)
这可以使用以下代码完成:
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;
}
});
Run Code Online (Sandbox Code Playgroud)
我在活动中添加了以下内容.它的工作原理是因为在可聚焦视图外触摸不会改变焦点(所以w == 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;
}
Run Code Online (Sandbox Code Playgroud)
[编辑:修复小错误]
| 归档时间: |
|
| 查看次数: |
33529 次 |
| 最近记录: |