关闭

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

446人阅读 评论(0) 收藏 举报
分类:

往上一堆乱七八糟的,比如修改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

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:294929次
    • 积分:4939
    • 等级:
    • 排名:第5757名
    • 原创:92篇
    • 转载:765篇
    • 译文:4篇
    • 评论:16条
    最新评论