活动片段管理器问题更改方向时:
Caused by: java.lang.IllegalStateException: Could not find active fragment with index -1 at
android.support.v4.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:3026) 在 android.support.v4.app.Fragment.restoreChildFragmentState(Fragment.java:1446) 在 android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1380) 在 android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740) 在 com.motors.mobile.core.v2.DaggerIncludeBaseActivity.onCreate(DaggerIncludeBaseActivity.java:26)
关注我的代码:
@Override
protected void tabletPortraitInit(Bundle savedInstanceState) {
super.tabletPortraitInit(savedInstanceState);
openSubFragment();
}
@Override
protected void tableLandscapeInit(Bundle savedInstanceState) {
super.tableLandscapeInit(savedInstanceState);
openSubFragment();
}
protected void openSubFragment() {
Bundle bundle = getIntent().getBundleExtra(CAR_DETAIL_KEY);
fragment = new BuyDetailFragment();
if (getSupportFragmentManager().findFragmentByTag(BuyDetailFragment.TAG) != null)
fragment = (BuyDetailFragment) getSupportFragmentManager().findFragmentByTag(BuyDetailFragment.TAG);
fragment.setArguments(bundle);
menuClickListener = fragment;
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.flMain, fragment, BuyDetailFragment.TAG)
.commit();
// init toolbar items
View tbView = getLayoutInflater().inflate(R.layout.items_detail_menu_layout, toolbar.findViewById(R.id.container), true);
phone = tbView.findViewById(R.id.phone);
message = tbView.findViewById(R.id.message);
link = tbView.findViewById(R.id.notifications);
site = tbView.findViewById(R.id.site);
shortlistView = tbView.findViewById(R.id.wishListMenu);
phone.setOnClickListener((e) -> menuClickListener.clickPhone());
message.setOnClickListener((e) -> menuClickListener.clickMessage());
link.setOnClickListener((e) -> menuClickListener.clickNotifications());
site.setOnClickListener((e) -> menuClickListener.clickSite());
shortlistView.setOnClickListener((e) -> menuClickListener.clickShortlist());
Drawable drawable = ContextCompat.getDrawable(this, R.drawable.vector_heart);
drawable.setColorFilter(ContextCompat.getColor(this, R.color.colorAccent), PorterDuff.Mode.SRC_IN);
shortlistView.changeIcon(drawable);
}
There is no my baseActivity
答案 0 :(得分:1)
您的片段是否有setRetainInstance(true)
?如果是这样,这可能会导致您遇到问题,特别是如果您正在使用FragmentStatePagerAdapter的片段。
答案 1 :(得分:0)
这可能发生在 dismissAllowingStateLoss 和 onSaveInstanceState 之后的 retainInstanceState 组合。
查看此helpful example with steps to reproduce(该站点不允许发表评论,但它帮助我诊断了问题)
重现步骤:
在幕后发生的事情是 FragmentManagerImpl.restoreAllState 现在有一个索引为 -1 的活动片段,因为dismissAllowingStateLoss 从后台堆栈中删除了片段,但是,它仍然是 nonConfigFragments 的一部分,因为dismissAllowingStateLoss 的提交部分被忽略,因为它是在 onSaveInstanceState 之后调用的。
要解决此问题将需要以下其中一项:
并以不同的方式实现所需的行为。