Strange fragment life cycle behavior: onCreate called twice

I created a simple snippet.

CLASS FRAGMENTS

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; } } 

But the fact is that the onCreate fragment is called twice (when the activity is started for the first time). Does anyone have an idea why? In fact, every lifecycle method is called twice (onAttach, onResume ..). I'm not a spinning screen or anything else if anyone might be surprised. Is this commonplace or am I doing something wrong here?

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); } } } 
+4
source share
1 answer

By default, the FragmentStatePagerAdapter will create two pages for the ViewPager. The onCreate function is called twice, once for each fragment returned by public Fragment getItem(int position)

0
source

Source: https://habr.com/ru/post/1486786/


All Articles