当计数相同时,如何通知 PagerAdapter 片段已更改?

How do you notify a PagerAdapter that the fragments have changed when the count is the same?

我构建了一个左侧导航栏的应用程序,其主要内容是一个 ViewPager

ViewPager 在两个不同的视图之间滑动。

当用户从导航栏中选择某些内容时,我会向 ViewPager 的适配器发送一条消息(为此我尝试了 FragmentPagerAdapter 和 FragmentStatePagerAdapter,两者都不起作用),它会设置一个内部变量并调用 notifyDatasetChanged() ;

问题是 getCount() 方法总是 returns 2 ,所以当适配器检查数据集是否发生变化时,它看到项目仍然是 2 并且不会继续调用getItem(位置).

getItem(position)returns根据notifyDatasetChanged()之前设置的内部变量的值进行不同的片段;

我尝试重写 getItemId(position) 以防寻呼机检查 id,但在检查计数后它似乎不会打扰。

有没有办法在调用 notifyDatasetChanged() 时强制适配器重建片段?

提前感谢您提供的任何帮助

编辑:这是我目前使用的代码:

public class ContentAdapter extends FragmentPagerAdapter {

    private ViewedSection _section = ViewedSection.Main;

    public ContentAdapter(FragmentManager fm) {
        super(fm);
    }
    @Override
    public Fragment getItem(int position) {
        ViewedScreen screen = get_screen(position);
        return screen == null ? null : FragmentFactory.GetFragment(get_screen(position));
}

    @Override
    public int getCount() {
        return 2;
    }

    private ViewedScreen get_screen(int position) {
    //code to resolve which screen will be shown according to the current position and _section
    }

    public void set_page(ViewedSection section) {
        this._section = section;
        notifyDataSetChanged();
    }
} 

所以当用户点击 NavBar 项目时,我调用 ((ContentAdapter)_pager.getAdapter()).set_page(section);

为此,您需要覆盖

    public int getItemPosition (Object object)

Return POSITION_UNCHANGED 如果你不想替换片段。 Return POSITION_NONE 如果要替换片段。 (另外,您可以 return 将片段移动到的新位置。)

一个常见的覆盖是

    public int getItemPosition (Object object) {
        return POSITION_NONE;
    }

这将重建一切。