因此,当我点击非EditText
视图时,我发现这段非常酷的代码可以解除键盘。除了使用getChildFragmentManager()
开始的Fragments和DialogFragments之外,它的效果非常好。有人请说明为什么例外以及我如何解决它?
public static void setupUI(View view, final Activity activity) {
// Set up touch listener for non-text box views to hide keyboard.
if (!(view instanceof EditText)) {
view.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
LayoutUtils.hideSoftKeyboard(activity);
return false;
}
});
}
// If a layout container, iterate over children and seed recursion.
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
setupUI(innerView, activity);
}
}
}
private static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity
.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
我将代码保存在实用程序类中,并在整个应用程序中使用它。基本上,对于问题情况,我在FragmentB上使用它是由FragmentA使用getChildFragmentManager()
启动的,然后代码不会影响FragmentB的视图。
答案 0 :(得分:0)
尝试隐藏键盘,
public void hideSoftKeyboard() {
try {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
} catch (Exception e) {
e.printStackTrace();
}
}
答案 1 :(得分:0)
尝试以下代码:
@Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
答案 2 :(得分:0)
如果您正在使用片段,请使用FragmentActivity而不是Activity。我建议使用try catch。
喜欢
try{
InputMethodManager inputMethodManager = (InputMethodManager) activity
.getSystemService(Activity.INPUT_METHOD_SERVICE);
}catch(Exception){
InputMethodManager inputMethodManager = (InputMethodManager) fragmentactivity.getSystemService(Activity.INPUT_METHOD_SERVICE);
}
答案 3 :(得分:0)
我找到了解决方案。也许其他人会发现它很有用
public static void setupUI(View view, final Activity activity) {
// Set up touch listener for non-text box views to hide keyboard.
if (!(view instanceof EditText)) {
view.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
LayoutUtils.hideSoftKeyboard(activity,v);
return false;
}
});
}
// If a layout container, iterate over children and seed recursion.
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
setupUI(innerView, activity);
}
}
}
private static void hideSoftKeyboard(Activity activity, View v) {
InputMethodManager inputMethodManager = (InputMethodManager) activity
.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
了解如何将activity.getCurrentFocus()
替换为v
。就是这样。它现在适用于所有情况。