My Problem
I'm developing a little app to test ViewPager
with FragmentStatePagerAdapter
. The app displays a TextView
. The content of the TextView
changes for each page of the ViewPager
. If I set the maximum amount of pages to a low number, it's working fine. But I need a page for each day since the beginning of the epoch. When I set getCount()
to getDaysSinceEpoche()
the app stops working properly. It takes up to a minute to change a page.
My question
What is causing this problem?
Maybe the FragmentStatePagerAdapter is not deleting the unused Fragments?
Edit
The getCount() method is getting called 16 times for each swipe. Why is this happening?
Adapter class
public class CustomViewPagerAdapter extends FragmentStatePagerAdapter{
public CustomViewPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
return FirstFragment.newInstance(i, "xyz");
}
@Override
public int getCount() {
return getDaysSinceEpoch();
}
public int getDaysSinceEpoch() {
Calendar now = Calendar.getInstance();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(0); // start at EPOCH
int days = 0;
while (cal.getTimeInMillis() < now.getTimeInMillis()) {
days += 1;
cal.add(Calendar.DAY_OF_MONTH, 1); // increment one day at a time
}
return days;
}
Fragment class
public class FirstFragment extends android.support.v4.app.Fragment {
private String title;
private int page;
public static FirstFragment newInstance(int page, String title){
FirstFragment firstFragment = new FirstFragment();
Bundle args = new Bundle();
args.putInt("int", page);
args.putString("string", title);
firstFragment.setArguments(args);
return firstFragment;
}
//Store instance variables based oj the arguments passed
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("int", 0);
title = getArguments().getString("string" );
}
//Inflate the View for the fragment based on xml layout
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
TextView tv = (TextView) view.findViewById(R.id.tv);
tv.setText(page + " -- " + title);
return view;
}