// 延迟5秒改变文字. 如果立刻执行, mFragment1 肯定是 null.
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (mFragment1 != null) {
mFragment1.setText("Every program must have a purpose. If not, it is deleted. -- The Matrix");
}
}
}, 5000);
}
private class SlidePagerAdapter extends FragmentPagerAdapter {
public SlidePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Fragment1();
case 1:
return new Fragment2();
case 2:
return new Fragment3();
default:
return null; // unlikely to happen
}
}
@Override
public int getCount() {
return 3;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
switch (position) {
case 0:
mFragment1 = (Fragment1) fragment;
break;
case 1:
mFragment2 = (Fragment2) fragment;
break;
case 2:
mFragment3 = (Fragment3) fragment;
break;
}
return fragment;
}
}
}
因为 instantiateItem() 方法管理了 Fragment 的创建及重用, 因此无论其是新创建的, 还是被恢复的, 都可以正确取到引用.