如何使用FragmentStateAdapter和ViewPager2在选项卡更改时停止刷新片段?

mkh04yzy  于 2023-06-30  发布在  Android
关注(0)|答案(1)|浏览(168)

我在我的Android项目中使用了FragementStateAdapter和ViewPager2。但问题是我的片段在标签更改时被重新加载。我想阻止它怎么做?我已经尝试了许多在线方法,如指定setOffScreenLimit等,但没有什么对我不起作用。这是我的代码
下面是我的适配器代码

public class LandingAdapter extends FragmentStateAdapter {

    private final List<Fragment> mFragmentList = new ArrayList<>();

    public LandingAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle) {
        super(fragmentManager, lifecycle);
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        return mFragmentList.get(position);
    }


    @Override
    public int getItemCount() {

        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment) {

        mFragmentList.add(fragment);
    }

    @Override
    public long getItemId(int position) {

        return mFragmentList.get(position).hashCode();
    }

}

这是我的活动代码

ViewPager2 mViewPager = findViewById(R.id.ViewPager);
        TabLayout mTabLayout = findViewById(R.id.TabLayout);


        LandingAdapter mAdapter = new LandingAdapter(getSupportFragmentManager(), getLifecycle());
        mViewPager.setAdapter(mAdapter);
        int savedAppMode = SharedPrefs.getInt(this, "app_mode_checked_item",0);
        if (savedAppMode == 1) {
            mAdapter.addFragment(new ItemsFrag1());
            mAdapter.addFragment(new ContactsFrag1());
            mAdapter.addFragment(new ImagesFrag1());
        } else {
            mAdapter.addFragment(new ItemsFrag2());
            mAdapter.addFragment(new ContactsFrag2());
            mAdapter.addFragment(new ImagesFrag2());
        }

        new TabLayoutMediator(mTabLayout, mViewPager, (tab, position) -> {
            switch (position) {
                case 0:
                    tab.setText("Items");
                    tab.setIcon(R.drawable.x_icon_photo);
                    break;
                case 1:
                    tab.setText("Contacts");
                    tab.setIcon(R.drawable.x_icon_video);
                    break;
                case 2:
                    tab.setText("Images");
                    tab.setIcon(R.drawable.x_icon_download);
                    break;
            }
        }).attach();
knpiaxh1

knpiaxh11#

您需要在使用FragmentPagerAdapter的片段的onCreate()中调用setRetainInstance(true)。
或者
你可以用limit

int limit = (adapter.getCount() > 1 ? adapter.getCount() - 1 : 1);
mViewPager = (ViewPager)findViewById(R.id.pager);
mViewPager.setOffscreenPageLimit(limit);

相关问题