Android 切换 Fragment 时隐藏键盘

11

当我更改片段时,我会使用这个来关闭键盘,因为屏幕上有一个EditText字段。我只是觉得一定有更好的方法,但我没有找到任何关于检测键盘是否在屏幕上的信息。

Activity activity = getActivity();
InputMethodManager inputMethodManager = (InputMethodManager)  activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
try
{
    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
catch (Exception e)
{

}

检测键盘有些困难,API 真正能做的只是触发键盘。 - Jared Burrows
3个回答

4
在实现调用多个片段的活动中,请添加以下内容...
    InputMethodManager imm = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);

0
您可以在暂停方法中使用以下代码:
@Override
protected void onPause() {
    super.onPause();

    final InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
    if (inputMethodManager != null && inputMethodManager.isActive()) {
        if (getCurrentFocus() != null) {
            inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }
}

-1

我能想到的唯一真正的方法是使用 onConfigurationChanged(Configuration config) 方法:

KeyboardHiddenConfiguration 的组合应该可以做到。

class MyFrag extends Fragment{

  @Override
  public void onConfigurationChanged(Configuration config){
    //Check flags
    switch(config.keyboardHidden){
      case KEYBOARDHIDDEN_NO:
        // do something
        break;
      case KEYBOARDHIDDEN_YES:
        break;
    }
  }

}

当然,这需要您拥有清单和父活动来接受这些作为配置更改:

<activity ...
  android:configChanges="keyboardHidden|orientation|screenSize|screenLayout"/>

此外,您会注意到Activity有相同的可重写方法,Activity将首先获取该方法,然后将其传递给附加的Fragment
对于敏锐的观察者,您可以使用上下文动态执行此操作:
Configuration config = getResources().getConfiguration();

希望这有所帮助,它旨在考虑硬键盘,但我相信你会遇到一些特定于设备的错误!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接