首页 > 解决方案 > 您的活动尚未附加到应用程序实例。您不能在 onCreate 调用之前请求 ViewModel

问题描述

我尝试在其托管活动中锚定到 viewId 的 fragmentDialog 上运行测试

  @Test
  public void largeScreenDeviceUsesPopup() {
    final FragmentUtilActivity fragmentActivity = new FragmentUtilActivity();
    fragmentActivity.onCreate(null);

    myDialogFragment = MyDialogFragment.create(FragmentUtilActivity.anchorId);
    myDialogFragment.showNow(fragmentActivity.getSupportFragmentManager(), "");

    assertThat(....)
  }

  private static class FragmentUtilActivity extends FragmentActivity  {

  public static int anchorId = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      LinearLayout view = new LinearLayout(this);
      view.setId(anchorId);

      setContentView(view);
    }
  }

但是我收到此错误:

Your activity is not yet attached to the Application instance. You can't request ViewModel before onCreate call.

我怎样才能解决这个问题?

标签: androidandroid-activityfragmentandroid-fragmentactivity

解决方案


推荐阅读