在碎片中隐藏EditText的键盘
问题描述:
我正在使用android studio。我在我的片段页面中编辑文本,现在我想在单击EditText外部后隐藏键盘。我使用下面的代码,但它不工作。在碎片中隐藏EditText的键盘
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final InputMethodManager imm = (InputMethodManager)
getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(locationEt.getWindowToken(), 0);
}
由于提前
答
尝试设置一个onFocusChangeListener
您EditText
。在onFocusChange方法中,你可以像这样隐藏键盘:
mEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(locationEt.getWindowToken(), 0);
}
});
答
试试这个在下面的函数中传递activity。有用。
public static void hideKeyboard(Activity activity) {
// Check if no view has focus:
View view = activity.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
答
请点击你的父母布局中使用下面的代码:
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
答
写这个代码到你的Activity
您的片段放置。
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
View view = getCurrentFocus();
boolean ret = super.dispatchTouchEvent(event);
if (view instanceof EditText) {
try {
View w = getCurrentFocus();
int scrcords[] = new int[2];
w.getLocationOnScreen(scrcords);
float x = event.getRawX() + w.getLeft() - scrcords[0];
float y = event.getRawY() + w.getTop() - scrcords[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);
if (getWindow() != null && getWindow().getCurrentFocus() != null) {
imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return ret;
}
快乐编码!
答
试试这个它的活动以及片段
public void setupUI(View view) {
if (!(view instanceof EditText)) {
view.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
//code of hide soft keyboard
return false;
}
});
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
setupUI(innerView);
}
}
}
答
使用这种方法工作时
txtHeader.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hideKeyboard(txtHeader);
}});
请尽量将外面或其他视图点击事件
像这样一个http://stackoverflow.com/questions/4165414/how-to-hide-soft-keyboard-on-android-after-clicking-outside-edittext –