My application have an activity which contains Fragment with view pager. View pager instantiate fragments, in which i load data from internet and display it. I have about 60 fragments always in view pager(its dates: today + 30 days before, 30 days after).
Problem is that when i changes orientation data begin download again. How to save state of this fragment?
Here is view pager adapter :
public class TimesheetPagerAdapter extends FragmentStatePagerAdapter {
private DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
private DateFormat dateTitleFormatted = new SimpleDateFormat("MMM dd - EEEE", Locale.US);
private ArrayList<Date> mDates;
public TimesheetPagerAdapter(FragmentManager fm, ArrayList<Date> mDates) {
super(fm);
this.mDates = mDates;
}
@Override
public Fragment getItem(int i) {
return TimesheetPage.newInstance(dateFormat.format(mDates.get(i)));
}
@Override
public int getCount() {
return mDates.size();
}
}
And ViewPager Fragment :
public static TimesheetPage newInstance(String page) {
TimesheetPage TimesheetPage = new TimesheetPage();
Bundle arguments = new Bundle();
arguments.putString("date", page);
TimesheetPage.setArguments(arguments);
return TimesheetPage;
}
@Override
public void onCreate(Bundle savedInstanceState) {
setRetainInstance(true);
super.onCreate(savedInstanceState);
dateString = getArguments().getString("date");
Random rnd = new Random();
backColor = Color.argb(50, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.item_pager_timesheet, null);
LinearLayout layout = (LinearLayout) view.findViewById(R.id.llPageLayout);
tvPage = (TextView) view.findViewById(R.id.tvAmountHours);
mLoadingLayout = LoadingLayout.wrap(layout, android.R.attr.progressBarStyle);
lvTimesheet = (ListView) view.findViewById(R.id.lvTimesheet);
tvPage.setBackgroundColor(backColor);
long id = getController().getUserAccount().getCompany().getCompanyId();
mLoadingLayout.showLoading();
Log.i("onCreateView", "TimesheetPage" + dateString);
getController().getNetworkApi().getCompanyTimeSheet(id, dateString, timesheetCallback);
return view;
}
I would recommend you to let the fragment recreate, but save your network call in your application cache to avoid querying every time. You can use a library like ion that use disk+memory cache: https://github.com/koush/ion
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.