I have a MainActivity in the markup of which there is a FrameLayout (fragment container). when I launch the Activity, I load a fragment into this container. On the RecyclerView and CardView fragment, further by clicking on an element, I upload a new fragment with a detailed description to the same container. Everything works, but when the device orientation changes, the second fragment is lost and only the first one with the list is shown. This is because I load the first fragment into the container in the onCreate method and when the activity is recreated, it loads, and the second fragment is loaded only by clicking on the item, the processing of the click occurs in the fragment. How do I solve this problem?

activation code

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragment = new FragmentList(); fragmentTransaction.replace(R.id.conteiner, fragment); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } 

download code of the second fragment

  public void onItemClick(View view, int position) { Item item = itemArrayList.get(position); Fragment fullArticleFragment = new FullArticleFragment(); Bundle bundle = new Bundle(); bundle.putString("url", item.getLink()); fullArticleFragment.setArguments(bundle); FragmentManager fragmentManager = getFragmentManager(); fragmentManager.beginTransaction().addToBackStack(null).replace(R.id.conteiner, fullArticleFragment).commit(); } 

    1 answer 1

    When you rotate, not only activations but also all fragments are recreated, but if you recreate an activation and create a fragment yourself, then it replaces the auto-recreated state with a restored state with a new one with the initial state. You do not need to manually re-create your fragment in onCreate activation if the state is being restored, for this you need to add a condition:

     @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragment = new FragmentList(); fragmentTransaction.replace(R.id.conteiner, fragment); fragmentTransaction.commit(); } } 

    And by the way, why do you add the initial fragment to the back stack? What if you clicked back it was removed from the activation and it remained empty?)

    Alternatively, if your screen layout on activations and fragments does not depend on the orientation of the screen, you can simply disable the re-creation of activations when you change the orientation by adding the attribute android:configChanges="orientation|screenSize|keyboardHidden" in the description of the activation in the manifest android:configChanges="orientation|screenSize|keyboardHidden"