FragmentPagerAdapter notifyDataSetChanged 不起作用的彻底解决方式

往上一堆乱七八糟的,比如修改initiateItem,增加flag等,但是其实最好最简单的也是

把FragmentPagerAdapter换成 

FragmentStatePagerAdapter
这样就解决了不更新的问题

public class MyFragmentAdapter extends FragmentStatePagerAdapter {
   private int length ;

   private ArrayList<Fragment> mFragments;//碎片数组
   private int mCount;
   FragmentManager fm ;
   public MyFragmentAdapter(FragmentManager fm , ArrayList<Fragment> mFragments) {
      super(fm);
      this.fm = fm;
      this.length = mFragments.size();
      this.mFragments = mFragments;
      FragmentTransaction mTransaction = fm.beginTransaction();
   }

   @Override
   public int getItemPosition(Object object) {
      return POSITION_NONE; //这个是必须的
   }

   @Override
   public Fragment getItem(int position) {
      int size = mFragments.size();
      if(position >= size)
         return mFragments.get(size - 1);
      return mFragments.get(position);
   }

   @Override
   public int getCount() {
      if(mCount > 0) {
         return mCount;
      } else {
         return length;
      }
   }

   public void setFragments(ArrayList<Fragment> fragments) {
      if(this.mFragments != null){
         FragmentTransaction ft = fm.beginTransaction();
         for(Fragment f:this.mFragments){
            ft.remove(f);
         }
         ft.commit();
         ft=null;
         fm.executePendingTransactions();
      }
      this.mFragments = fragments;
      notifyDataSetChanged();
   }

   public void setMaxCount(int count) {
      if(mCount < length) {
         if(mCount != count) {
            mCount = count;
            notifyDataSetChanged();
         }
      }
   }

   public void setmFragments(ArrayList<Fragment> mFragments) {
      this.mFragments = mFragments;
   }
}

详细请参考

http://stackoverflow.com/questions/10849552/update-viewpager-dynamically

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sd19871122/article/details/51538205
个人分类: android
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

FragmentPagerAdapter notifyDataSetChanged 不起作用的彻底解决方式

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭