我的问题
我正在开发一个小应用程序来用ViewPager
测试FragmentStatePagerAdapter
。该应用程序显示一个TextView
。 TextView
的内容随ViewPager
的每一页而变化。如果我将最大页面数设置为一个低数字,则可以正常工作。但自纪元开始以来,我每天都需要一页。当我将getCount()
设置为getDaysSinceEpoche()
时,应用程序将停止正常运行。更改页面最多需要一分钟。
我的问题
是什么引起了这个问题?
也许FragmentStatePagerAdapter不会删除未使用的Fragments?
修改
每次滑动getCount()方法都会被调用16次。为什么会这样?
适配器类
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;
}
片段类
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;
}