I know it's a bit late to answer, but using "Reply to the Code", you can do the following:
If a fragment exists in the backstack, we drop it and delete it to add it back (an exception is thrown if it is added back without deleting it, if it already exists).
The fragment variable is a member variable of the class.
This method will be called in the onCreate Activity method:
if (savedInstanceState == null) { FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); if (fragmentManager.findFragmentById(getFragmentActivityLayoutContainerId()) == null) { fragment = getNewFragmentInstance(); } else { fragment = fragmentManager.findFragmentById(getFragmentActivityLayoutContainerId()); fragmentTransaction.remove(fragment); fragmentManager.popBackStack(); fragmentTransaction.commit(); fragmentTransaction = fragmentManager.beginTransaction(); } fragmentTransaction.add(getFragmentActivityLayoutContainerId(), fragment); fragmentTransaction.commit(); }
The following code will be called in the fragment itself.
This is a small example of code that you could implement in your snippet to understand how it works. DummyTV is a simple text view in the center of the fragment, which receives the text in accordance with the orientation (and for this we need a counter).
private TextView dummyTV; private static int counter = 0; @Override protected int getFragmentLayoutId() { return R.layout.fragment_alerts_view; } @Override protected void saveReferences(View view) { dummyTV = (TextView) view.findViewById(R.id.fragment_alerts_view_dummy_tv); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { if (savedInstanceState != null) { dummyTV.setText(savedInstanceState.getString("dummy_string")); } else { dummyTV.setText("flip me!"); } dummyTV.append(" | " + String.valueOf(counter)); } @Override public void onSaveInstanceState(Bundle outState) { outState.putString("dummy_string", counter++ % 2 == 0 ? "landscape" : "portrait"); }
source share