ViewPager+TabLayout+Fragment刷新Fragment中的数据
Posted jeffery336699
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ViewPager+TabLayout+Fragment刷新Fragment中的数据相关的知识,希望对你有一定的参考价值。
1.ViewPager与TabLayout的初始化:
private void initData() {
mTabFragmentAdapter = new TabFragmentFirstAdapter(getSupportFragmentManager(), mDeptType);
mVp.setAdapter(mTabFragmentAdapter);
mVp.addOnPageChangeListener(
new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
mVp.setOffscreenPageLimit(3);
mTabLayout.setupWithViewPager(mVp);
}
8
8
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()
private void reflashData(int type, List<WorkOrderBean.RowsBean> list) {
mTabFragmentAdapter.setDataAndType(type, list);
mTabFragmentAdapter.notifyDataSetChanged();
}
4
4
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
@Override
public int getItemPosition(Object object) {
if (object instanceof WorkSubFirstFragment) {
if (list0.size()==0)return super.getItemPosition(object);
((WorkSubFirstFragment) object).updateView(list0);
} else if (object instanceof WorkSubFirstFragment1) {
if (list1.size()==0)return super.getItemPosition(object);
((WorkSubFirstFragment1) object).updateView(list1);
} else if (object instanceof WorkSubFirstFragment2) {
if (list2.size()==0)return super.getItemPosition(object);
((WorkSubFirstFragment2) object).updateView(list2);
}
return super.getItemPosition(object);
}
14
1
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中的更新视图方法:
public void updateView(List<WorkOrderBean.RowsBean> rows) {
reflashSelfData(rows);
}
x
1
public void updateView(List<WorkOrderBean.RowsBean> rows) {
2
reflashSelfData(rows);
3
}
小贴士:
添加数据时不要直接赋值,采用addList()方法最好,并且之前最好清空数据集
list0.clear();
list0.addAll(list);
x
1
list0.clear();
2
list0.addAll(list);
以上是关于ViewPager+TabLayout+Fragment刷新Fragment中的数据的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Android 中使用 TabLayout 和 ViewPager2
片段中的Tablayout + viewpager,需要清除viewpager中的edittext数据