如何在FragmentPagerAdapter中更改位置时重新加载和刷新片段?

时间:2017-09-20 07:27:17

标签: android android-fragments

每次切换时,我都需要重新加载操作并刷新片段 FragmentPagerAdapter 我看过

的引用
  

ViewPager PagerAdapter not updating the View

     

How to refresh a Fragment of a FragmentPagerAdapter?

My FragmentPagerAdapter

public class SickAdapterApproval extends FragmentPagerAdapter{

    private static final int FRAGMENT_COUNT = 4;

    public SickAdapterApproval(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position){
            case 0:
                return new SickFragmentToAll();
            case 1:
                return new SickFragmentToPending();
            case 2:
                return new SickFragmentToApproved();
            case 3:
                return new SickFragmentToDenied();
        }
        return null;
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position){
            case 0:
                return "All";
            case 1:
                return "Pending";
            case 2:
                return "Approved";
            case 3:
                return "Denied";
        }
        return null;
    }
}

但我仍然坚持并且不明白,是否有人可以向我解释并举例说明?

2 个答案:

答案 0 :(得分:1)

使用`FragmentStatePageAdapater

更改FragmentPageAdapter

并覆盖此方法:

@Override
public int getItemPosition(Object object) {
//FragmentLeft is the class for the first fragment in the view
//recreate only FragmentLeft
    if (object instanceof FragmentLeft) {
        return POSITION_NONE;
    }
    return 1;
}

答案 1 :(得分:0)

如果您只想刷新现有片段的内容,则解决方案中不涉及notifyDataSetChanged()和适配器。您需要确保为数据提供的视图得到刷新。查看我的source

  

notifyDatasetChanged()方法并不用于刷新当前显示的片段或其视图。如果您希望在某些数据更改时刷新其视图,则需要向片段添加一些侦听器/回调。