Android 当编辑文本失去焦点时关闭键盘
我有一个编辑文本,我想控制键盘。当EditText具有焦点时,键盘应该出现,然后只要我单击任何其他视图,我希望键盘消失。我尝试了以下代码,但它确实有效Android 当编辑文本失去焦点时关闭键盘,android,android-layout,keyboard,Android,Android Layout,Keyboard,我有一个编辑文本,我想控制键盘。当EditText具有焦点时,键盘应该出现,然后只要我单击任何其他视图,我希望键盘消失。我尝试了以下代码,但它确实有效 mEditText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (
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);
}
}
});
假设您最外层的布局是相对主义布局(您也可以对其他布局执行类似的操作),您可以执行以下操作:
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);
}
在这里的ontapoutsidebehavior
功能中,除了您的EditText
和按钮
视图之外,如果用户单击其他任何位置,它将隐藏键盘。如果有任何复杂的自定义布局,则可以排除其他视图,如果用户单击这些视图,则不会隐藏键盘
这对我有用。希望对您有所帮助。您是否仍有此问题?如果你还需要帮助,请告诉我。