我在Android项目中使用ViewPager,并使用FragmentStatePagerAdapter
来设置页面。
class MyPageAdapter extends FragmentStatePagerAdapter {
List<Fragment> mList = new ArrayList<>();
public MyPageAdapter(FragmentManager fm) {
super(fm);
this.init();
}
private void init() {
mList.add(new FragmentOne());
mList.add(new FragmentTwo());
mList.add(new FragmentThree());
....
}
@Override
public Fragment getItem(int position) {
return mList.get(position);
}
}
对于每个Fragment
数据,一旦创建视图,将从服务器加载数据,如下所示:
public class FragmentOne extends Fragment {
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(getViewResourceId(), container, false);
ButterKnife.bind(this, v);
setRetainInstance(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
mRecycleView.setLayotManager(linearLayoutManager);
endlessRecyclerViewScrollListener = new EndlessRecyclerViewScrollListener((LinearLayoutManager) mRecycleView.getLayoutManager()) {
@Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
loadByPage(page);
}
};
mRecycleView.addOnScrollListener(endlessRecyclerViewScrollListener);
return v;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mAdapter = createAdapter();
mRecycleView.setAdapter(mAdapter);
loadByPage(1); // load data from server
}
}
如图所示,Fragment
包含无尽的回收者视图。
到目前为止一切顺利。但是,一旦我更改了所选的视图页面,我发现每次都会重新加载数据。例如,我在FragmentOne
中滚动了3个页面,然后更改为FragmentTwo
,当我更改为FragmentOne
时,FragmentOne
将尝试加载第1页的数据。
有可能避免这种情况吗?
答案 0 :(得分:1)
您可以执行以下操作:
private boolean isDataCalled = true;
private List<ItemModel> itemModelList;
然后
if (isDataCalled){
loadByPage(1); // Initialize itemModelList in this method
setItemAdapter(itemModelList);
isDataCalled = false;
}else {
setItemAdapter(itemModelList);
}
setItemAdapter方法
private void setItemAdapter(List<ItemModel> itemModelList){
mAdapter = createAdapter(itemModelList);
mRecycleView.setAdapter(mAdapter);
}