Android:触摸EditText时隐藏软键盘
问题描述:
按下Back按钮或Done按钮时,隐藏softInputKeyboard的操作是隐藏键盘,当用户点击EditText时隐藏键盘。所以我创建了一个BaseActivity并在其中编写了以下代码。Android:触摸EditText时隐藏软键盘
public class BaseActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean handleReturn = super.dispatchTouchEvent(ev);
View view = getCurrentFocus();
int x = (int) ev.getX();
int y = (int) ev.getY();
if (view instanceof EditText) {
EditText innerView = (EditText) getCurrentFocus();
if (ev.getAction() == MotionEvent.ACTION_UP &&
!getLocationOnScreen(innerView).contains(x, y)) {
InputMethodManager input = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
input.hideSoftInputFromWindow(getWindow().getCurrentFocus()
.getWindowToken(), 0);
}
}
return handleReturn;
}
protected Rect getLocationOnScreen(EditText mEditText) {
Rect rect = new Rect();
int[] location = new int[2];
mEditText.getLocationOnScreen(location);
rect.left = location[0];
rect.top = location[1];
rect.right = location[0] + mEditText.getWidth();
rect.bottom = location[1] + mEditText.getHeight();
return rect;
}
}
为MyActivity扩展上述类,它在其布局上对EditTexts正常工作。但是,当我弹出一个AlertDialog与自定义布局,其中有许多EditText的时候它不起作用。
我触摸了AlertDialog中的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);
}
答
有两件事情要记住,以实现这一目标 -
假设XML struture就像
<ViewGroup focusable=true focusInTouchMode=true>
<EditText />
</ViewGroup>
- 使母公司的ViewGroup为可聚焦=真& focusInTouchMode = true
-
set
onfocuschangelistener()
上的EditText,即edittext.editCaption.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0); } });
我想你没有理解我的问题,上述...当我触摸到了一个AlertDialog具有自定义布局的键盘应该被隐藏 – user1799171