我有一个要控制键盘的 EditText。当 EditText 具有焦点时,键盘应该出现,然后只要我单击任何其他 View ,我希望键盘消失。我尝试了以下代码,但它确实有效
mEditText.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
} else {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
}
}
});
最佳答案
假设您的最外层布局是RelativeLayout
(您也可以为其他布局做类似的事情),您可以执行如下操作:
private RelativeLayout layout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//....
layout = (RelativeLayout) findViewById(R.id.yourOutermostLayout);
onTapOutsideBehaviour(layout);
}
private void onTapOutsideBehaviour(View view) {
if(!(view instanceof EditText) || !(view instanceof Button)) {
view.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
hideSoftKeyboard(YourCurrentActivity.this);
return false;
}
});
}
}
\\Function to hide keyboard
private static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
在此处的onTapOutsideBehaviour
函数中,除了您的EditText
和Button
View ,如果用户点击其他任何地方,它将隐藏键盘。如果您有任何复杂的自定义布局,您可以排除其他 View ,如果用户单击这些 View ,它不会隐藏键盘。
它对我有用。希望对你有帮助。
关于android - 当 EditText 失去焦点时关闭键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20979592/