10

当我改变片段时。我正在使用它来关闭键盘,因为屏幕上有一个 EditText 字段。我只是觉得必须有更好的方法,但我还没有发现任何关于检测键盘是否在屏幕上的东西。

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

}
4

3 回答 3

4

在您实现对各种片段的调用的活动中,放置以下内容......

    InputMethodManager imm = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
于 2014-08-25T02:19:22.893 回答
0

您可以在 pause 方法中使用以下代码:

@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);
        }
    }
}
于 2019-05-27T10:48:49.150 回答
-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具有相同的可覆盖方法,活动将首先获取该方法,然后将其传递给附加Fragment的 s。

对于观察者,您可以使用上下文即时执行此操作:

Configuration config = getResources().getConfiguration();

希望对您有所帮助,这也意味着要考虑硬键盘,但我相信您会遇到一些特定于设备的错误!

于 2013-02-05T00:11:28.070 回答