有一個片段,上面有四個標(biāo)簽。每個選項(xiàng)卡都有自己的片段。我使用第一個、第二個、第三個選項(xiàng)卡的片段來收集保存在我的 SharedPreferences 中的數(shù)據(jù),并在第四個選項(xiàng)卡中接收它。切換第四頁時,我想看到我從其他片段中選擇的信息。我的問題是只有第一個選項(xiàng)卡可以立即將數(shù)據(jù)傳遞到第四頁,無論我保存什么,它都可以立即顯示在第四頁,這就是我想要的。然而,其他人很奇怪我需要再多一步切換到第一個選項(xiàng)卡,它甚至可以將我的數(shù)據(jù)從其他選項(xiàng)卡更新到第四頁。我的代碼或訂單有什么問題導(dǎo)致這種情況發(fā)生?public class UserActivityMenuFragment extends Fragment {public static final String[] sTitle = new String[]{"first","second","third","fourth"};@Nullable@Overridepublic View onCreateView(@NonNull final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.menu_activity,container ,false); initView(view); return view;}private void initView(View view) { ViewPager mViewPager = view.findViewById(R.id.containerView); TabLayout mTabLayout = view.findViewById(R.id.tabs); mTabLayout.addTab(mTabLayout.newTab().setText(sTitle[0])); mTabLayout.addTab(mTabLayout.newTab().setText(sTitle[1])); mTabLayout.addTab(mTabLayout.newTab().setText(sTitle[2])); mTabLayout.addTab(mTabLayout.newTab().setText(sTitle[3])); mTabLayout.setupWithViewPager(mViewPager); List<Fragment> fragments = new ArrayList<>(); fragments.add(FirstFragment.newInstance()); fragments.add(SecondFragment.newInstance()); fragments.add(ThirdFragment.newInstance()); fragments.add(FourthFragment.newInstance()); UserActivityMenuAdapter adapter = new UserActivityMenuAdapter(getChildFragmentManager(),fragments, Arrays.asList(sTitle)); mViewPager.setAdapter(adapter); mViewPager.setOffscreenPageLimit(2); mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } });
2 回答

瀟湘沐
TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超6個贊
FragmentStatePagerAdapter 不保存任何 Fragment 實(shí)例,而是保存它們的 savedInstanceState。
如果一個 Fragment(page) 不可見,它的實(shí)例將保持銷毀狀態(tài),直到它再次可見,然后從savedInstanceState 重新創(chuàng)建。
如果您想讓所有 Fragment 保持活動狀態(tài),請使用 FragmentPagerAdapter 而不是 FragmentStatePagerAdapter。

HUX布斯
TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超6個贊
該ViewPager
不會一次創(chuàng)建的所有頁面。您可以使用以下代碼段強(qiáng)制它同時維護(hù)所有片段:
mViewPager.setOffscreenPageLimit(4);
添加回答
舉報
0/150
提交
取消