单击导航栏中的项目时,我有底部导航栏,我正在替换片段。我有 3 个片段 A、B、C,因此单击 b 项 B 片段已加载,并且在 B 中我正在调用 3-4 个 API。所以现在如果我去 C 然后再去 B 一个新的 B 片段实例被创建并且再次调用这些 API 我如何保存片段实例状态而不是在更改片段时再次调用 API。这是我的代码。
mBottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
Fragment currentLoaded = fgMan.findFragmentById(R.id.container_body);
switch (id) {
case R.id.nearby_fragment:
if (!(currentLoaded instanceof SpotFeedMapFragment)) {
removeScroll();
mNearByFragment = fgMan.findFragmentByTag(NEARBY_FRAGMENT_TAG) != null ? fgMan.findFragmentByTag(NEARBY_FRAGMENT_TAG) : mNearByFragment;
fgMan.beginTransaction().setCustomAnimations(R.anim.abc_fade_in, R.anim.abc_fade_out);
fgMan.beginTransaction().replace(R.id.container_body, mNearByFragment, NEARBY_FRAGMENT_TAG).commit();
fgMan.executePendingTransactions();
getSupportActionBar().setTitle(getString(R.string.nearby_fragment));
}
break;
case R.id.route_fragment:
if (!(currentLoaded instanceof BusLocationsFragment)) {
if (!inParent) {
mRl.removeView(fixLayout);
p.addRule(RelativeLayout.BELOW, toolbar.getId());
scrollView.setLayoutParams(p);
scrollView.addView(fixLayout);
mRl.addView(scrollView);
inParent = true;
}
//mFragment = new BusLocationsFragment();
mBusLocFragment = fgMan.findFragmentByTag(BUS_LOC_FRAGMENT_TAG) != null ? fgMan.findFragmentByTag(BUS_LOC_FRAGMENT_TAG) : mBusLocFragment;
fgMan.beginTransaction().setCustomAnimations(R.anim.abc_fade_in, R.anim.abc_fade_out);
fgMan.beginTransaction().replace(R.id.container_body, mBusLocFragment, BUS_LOC_FRAGMENT_TAG).commit();
fgMan.executePendingTransactions();
getSupportActionBar().setTitle(getString(R.string.app_name));
}
break;
case R.id.newsfeed_activity:
if (!(currentLoaded instanceof NewsFeedActivity)) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
removeScroll();
}
mNewsFeedFragment = fgMan.findFragmentByTag(NEWSFEED_FRAGMENT_TAG) != null ? fgMan.findFragmentByTag(NEWSFEED_FRAGMENT_TAG) : mNewsFeedFragment;
fgMan.beginTransaction().setCustomAnimations(R.anim.abc_fade_in, R.anim.abc_fade_out);
fgMan.beginTransaction().replace(R.id.container_body, mNewsFeedFragment, NEWSFEED_FRAGMENT_TAG).commit();
fgMan.executePendingTransactions();
getSupportActionBar().setTitle(getString(R.string.news));
}
break;
}
return true;
}
});
我已经在上面初始化了片段成员onCreate
变量MainActivity