ViewPager+TabLayout+Fragment刷新Fragment中的数据
1.ViewPager与TabLayout的初始化:
1 private void initData() { 2 mTabFragmentAdapter = new TabFragmentFirstAdapter(getSupportFragmentManager(), mDeptType); 3 mVp.setAdapter(mTabFragmentAdapter); 4 mVp.addOnPageChangeListener( 5 new TabLayout.TabLayoutOnPageChangeListener(mTabLayout)); 6 mVp.setOffscreenPageLimit(3); 7 mTabLayout.setupWithViewPager(mVp); 8 }
2.刷新主要还是靠FragmentPagerAdapter的notifyDataSetChanged()
1 private void reflashData(int type, List<WorkOrderBean.RowsBean> list) { 2 mTabFragmentAdapter.setDataAndType(type, list); 3 mTabFragmentAdapter.notifyDataSetChanged(); 4 }
3.当notify时,FragmentPagerAdapter中主要会回调getItemPosition(Object object)方法,在这里判断是哪个Fragment
1 @Override 2 public int getItemPosition(Object object) { 3 if (object instanceof WorkSubFirstFragment) { 4 if (list0.size()==0)return super.getItemPosition(object); 5 ((WorkSubFirstFragment) object).updateView(list0); 6 } else if (object instanceof WorkSubFirstFragment1) { 7 if (list1.size()==0)return super.getItemPosition(object); 8 ((WorkSubFirstFragment1) object).updateView(list1); 9 } else if (object instanceof WorkSubFirstFragment2) { 10 if (list2.size()==0)return super.getItemPosition(object); 11 ((WorkSubFirstFragment2) object).updateView(list2); 12 } 13 return super.getItemPosition(object); 14 }
4.定义Fragment中的更新视图方法:
1 public void updateView(List<WorkOrderBean.RowsBean> rows) { 2 reflashSelfData(rows); 3 }
小贴士:
添加数据时不要直接赋值,采用addList()方法最好,并且之前最好清空数据集
1 list0.clear(); 2 list0.addAll(list);