我创建了简单片段。
FRAGMENT CLASS
public class MyFragment extends Fragment {
static int count = 0;
static TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("TEST", "oncreate");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag, container, false);
tv = (TextView) view.findViewById(R.id.tv);
return view;
}
public static TextView setMyText(String text) {
tv.setText(text);
return tv;
}
}
但问题是onCreate片段被调用两次(当活动首次启动时)。任何人都知道为什么?实际上,每个生命周期方法都被调用两次(onAttach,onResume ..)。如果有人想知道,我不旋转屏幕或任何东西。这是常见的情况还是我在这里做错了什么?
ACTIVITY CLASS
public class MainActivity extends FragmentActivity {
private static int COUNT = 0;
private static int COUNT2 = 5;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_pager);
ViewPager vp = (ViewPager) findViewById(R.id.vp);
vp.setAdapter(new MyAdapter(getSupportFragmentManager()));
vp.setOnPageChangeListener(new CustomPageListener());
}
private static class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
MyFragment mf = new MyFragment();
return mf;
}
@Override
public int getCount() {
return 5;
}
}
private class CustomPageListener extends ViewPager.SimpleOnPageChangeListener {
@Override
public void onPageSelected(int position) {
MyFragment.setMyText("This is page "+position);
}
}
}
答案 0 :(得分:0)
默认情况下,FragmentStatePagerAdapter
将为ViewPager实例化两个页面。 onCreate被调用两次,对public Fragment getItem(int position)