Fragment onCreateView and onActivityCreated not being called on rotation - android

I am working with fragments and pushing new fragments on the backstack but when I rotate the device twice the fragment's onCreateView, onActivityCreated, and so on in the fragment life cycle methods are never called leaving a blank screen. This only occurs when a fragment has been added to the backstack or returning to the first fragment in the backstack.
Here is my activity's fragment handling methods:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Injection
MormonChannel.injectActivity(this);
setDrawerIndicatorEnabled(true);
// Do not set currentNavigationItem here.
NavigationItemSelectedEvent.NavigationItem navItem = null;
Intent intent = getIntent();
if (intent != null) {
navItem = (NavigationItemSelectedEvent.NavigationItem)
intent.getSerializableExtra(EXTRA_NAV_ITEM);
}
if (savedInstanceState == null) {
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().replace(R.id.container, new FeatureListFragment()).commit();
if (navItem != null) {
onNavigationItemSelected(new NavigationItemSelectedEvent(navItem));
} else {
currentNavigationItem = NavigationItemSelectedEvent.NavigationItem.FEATURES;
}
}
}
#Subscribe
public void onNavigationItemSelected(NavigationItemSelectedEvent event) {
if (currentNavigationItem == event.getNavigationItem()) {
return;
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.popBackStack();
NavigationItemSelectedEvent.NavigationItem navigationItem = event.getNavigationItem();
String name = navigationItem.getName();
switch (navigationItem) {
default:
case FEATURES:
// Nothing needs to be done it is already there.
break;
case AUDIO:
fragmentManager.beginTransaction().replace(R.id.container,
CollectionListFragment.newInstance(prefs.getLanguageId(), prefs.getAudioCollectionId()))
.addToBackStack
(name).commit();
break;
case VIDEO:
fragmentManager.beginTransaction().replace(R.id.container,
CollectionListFragment.newInstance(prefs.getLanguageId(), prefs.getVideoCollectionId()))
.addToBackStack(name).commit();
break;
case RADIO:
fragmentManager.beginTransaction().replace(R.id.container,
CollectionListFragment.newInstance(prefs.getLanguageId(), prefs.getRadioCollectionId()))
.addToBackStack(name).commit();
break;
case HISTORY:
fragmentManager.beginTransaction().replace(R.id.container, new HistoryFragment()).addToBackStack(name).commit();
break;
case DOWNLOADS:
fragmentManager.beginTransaction().replace(R.id.container, new DownloadsFragment()).addToBackStack(name).commit();
break;
case PLAYLISTS:
fragmentManager.beginTransaction().replace(R.id.container, new PlaylistFragment()).addToBackStack(name).commit();
break;
}
currentNavigationItem = navigationItem;
}
Here is my CollectionListFragment Code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MormonChannel.injectFragment(this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.collection_list_fragment, container, false);
ButterKnife.inject(this, v);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView.setDividerHeight(0);
listView.setFastScrollEnabled(true);
Bundle args = getArguments();
if (args != null) {
languageId = args.getLong(ARG_LANGUAGE_ID, -1L);
collectionId = args.getLong(ARG_COLLECTION_ID, -1L);
if (args.containsKey(ARG_SORT)) {
sort = (Sort) args.getSerializable(ARG_SORT);
}
}
if (collectionId == -1L || languageId == -1L) {
// TODO Implement Empty Collection Text
} else {
collection = collectionManager.findByCollectionId(languageId, collectionId);
getLoaderManager().initLoader(LOADER_ID, null, this);
}
titleEvent = new TitleChangeEvent(collection != null ? collection.getTitle() : getString(R.string.app_name));
bus.post(titleEvent);
}
Manifest for activity:
<activity
android:name=".activity.MainActivity"
android:launchMode="singleTask">
<meta-data
android:name="android.app.default_searchable"
android:value=".activity.SearchActivity"/>
</activity>

In your CollectionListFragment Code, add call to setRetainInstance() method in the onCreate() method, with true as its argument:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
MormonChannel.injectFragment(this);
}
Using setRetainInstance(true) ensures that when configuration changes occur activity will be killed but android will not destroy the fragment it is hosting.
Instead android will save the fragment state and detach the fragment from the activity. Also it wont destroy the fragment and so it wont create it later when hosting activity is created. So fragment will not receive calls to its onDestroy() and onCreate() methods.

Related

Android oncreateview called twice

I have see this question asked here more than one time but I can't figure it out how to solve for my case.
I have an app that the user does this:
1 - Open the navigationDrawer and selects one option (a fragment is created) (I'm here selecting the second option);
public void selectItem(int position) {
Fragment fragment = null;
switch (position) {
case FRAGMENT_OPTION1:
...
break;
case FRAGMENT_OPTION2:
fragment = ControlPanelFragment.newInstance();
break;
...
case FRAGMENT_OPTIONN:
...
return;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment_container, fragment).commitAllowingStateLoss();
}
}
2 - The selected option (ControlPanelFragment) gets loaded:
2.1 - Control panel has tabs and an iconpager. For each pager page and for each tab a new fragment is created. I have 3 tabs and 3 pages so 9 fragments are created;
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (savedInstanceState != null) {
currentControlPanelOption = savedInstanceState.getInt("currentControlPanelOption", currentControlPanelOption);
currentControlPanelTab = savedInstanceState.getInt("currentControlPanelTab", currentControlPanelTab);
}
setControlPanelTabs();
setIconPager();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("currentControlPanelOption", pager.getCurrentItem());
outState.putInt("currentControlPanelTab", mTabHost.getCurrentTab());
}
3 - In the setIconPager(); I have this code:
pager = (ViewPager) view.findViewById(R.id.pager);
cPanelPagerAdapter = new ControlPanelPagerAdapter(getChildFragmentManager());
pager.setOffscreenPageLimit(2);
pager.setAdapter(cPanelPagerAdapter);
where ControlPanelPagerAdapter has this code:
public Fragment getItem(int index) {
Fragment fragment;
switch (index) {
case 1:
fragment = FragmentA.newInstance();
break;
case 2:
fragment = FragmentB.newInstance();
break;
case 3:
fragment = FragmentC.newInstance();
break;
default:
fragment = null;
break;
}
...
return fragment;
}
4 - FragmentA, FragmentB and FragmentC have almost the same code:
public static FragmentA newInstance() {
return new FragmentA();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_placeholder, container, false);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (savedInstanceState == null) {
fragmentA_Data = new FragmentADetail[3];
createTabInstance(0);
} else {
fragmentA_Data = (FragmentADetail[]) savedInstanceState.getSerializable("Data");
return;
}
}
private void createTabInstance(int tab) {
new FragmentADetail();
fragment = FragmentADetail.newInstance(tab);
Bundle args = new Bundle();
args.putInt("tab", tab);
fragment.setArguments(args);
fragmentA_Data[tab] = fragment;
FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_placeholder, fragmentA_Data[tab]);
fragmentTransaction.commitAllowingStateLoss();
}
public void getTabData(int tab) {
if (fragmentA_Data[tab] == null) {
createStoreTimePeriodInstance(tab);
} else {
if (fragmentA_Data[tab].getArguments() == null) {
Bundle args = new Bundle();
args.putInt("tab", tab);
fragmentA_Data[tab].setArguments(args);
}
FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_placeholder, fragmentA_Data[tab]);
fragmentTransaction.commitAllowingStateLoss();
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("data", fragmentA_Data);
}
5 - Finally, FragmentADetail has this code:
public static FragmentADetail newInstance(int tab) {
selectedTab = tab;
return new FragmentADetail();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.details_fragment, container, false);
...
if (savedInstanceState != null) {
selectedTab = savedInstanceState.getInt("selectedTab");
}
...
}
public void getTabData(int tab) {
//This is where I'm getting the data that populates the layout
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("selectedTab", selectedTab);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle args = getArguments();
if (args != null) {
getTabData(args.getInt("tab"));
}
}
Now, imagine I'm on FragmentA with the third tab selected. If I rotate the screen I have this sequence of events:
ControlPanelFragment onSaveInstanceState saves the current tab and current fragment
FragmentA onSaveInstanceState saves the tabs fragments for the pager
navigationDrawer second option gets again called fragment = ControlPanelFragment.newInstance();
ControlPanelFragment onViewCreated is called and I can get the saved data information and a new pager and tabs are created
FragmentA onViewCreated is called and I can extract the saved data
FragmentADetail onActivityCreated gets the saved data and loads the data correctelly (at least I think)
And from now a second set of methods is called the second time and the data that was previously saved is reseted and so it now displays wrong data
ControlPanelFragment onSaveInstanceState but now the savedInstanceState is null
ControlPanelPagerAdapter getItem is called instantiating the 3 fragments
FragmentA onSaveInstanceState its now called but savedInstanceState is null
FragmentADetail onActivityCreated is called but now the tab = 0
Can someone explain-me how can I stop steps 7 to 10 from happening?
I figure out what was my problem.
When I was doing:
case FRAGMENT_OPTION2:
fragment = ControlPanelFragment.newInstance();
break;
I was creating a fragment and when I rotated the screen selectItem(int position) was again called so a new instance of the same object was created thus the steps 7 and following. The solution was to check if the fragment was already created and use him instead of creating a new one.
I've saved the initial fragment with a tag and them looked for that tag. If the tag existed, use that fragment otherwise create a new one.
public void selectItem(int position) {
Fragment fragment = null;
switch (position) {
case FRAGMENT_OPTION1:
...
break;
case FRAGMENT_OPTION2:
fragment = getSupportFragmentManager().findFragmentByTag(String.valueOf(position));
if (fragment == null) {
fragment = ControlPanelFragment.newInstance();
}
break;
...
case FRAGMENT_OPTIONN:
...
return;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment_container, fragment,
String.valueOf(position)).commitAllowingStateLoss();
}
}

Fragment is re-created after back from Activity

I have a problem related to fragment life cycle.
Before doing this, I will set DONT KEEP ACTIVITY mode(Setting -> Developer options).
In my project have 2 activity:
Activity 1: keep and control Fragment A and Fragment B
Activity 2: do not have fragment.
Activity 1 will be called first, then Fragment A and Fragment B will be called to visible.
Start Activity 2 from Activity 1, this cause Activity 1 will be destroyed and Fragment A & Fragment B will be destroyed too (Because of dont keep activity mode).
Press back key from Activity 2 to back Activity 1
Problem occurs here: Fragment A and Fragment B will be automatically called onCreateView() after back from activity 2 -> I want to avoid this. Can you give me some tips to resolve it?
Update Code
Activity 1
public class MainActivity extends Activity implements OnClickListener {
private Button mBtnShowFragmentA;
private Button mBtnShowFragmentB;
private Button mBtnGoAcitivity2;
protected String mCurrentFragmentTag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_activity_1);
mBtnShowFragmentA = (Button) findViewById(R.id.btn_show_fragmentA);
mBtnShowFragmentB = (Button) findViewById(R.id.btn_show_fragmentB);
mBtnGoAcitivity2 = (Button) findViewById(R.id.btn_go_activity2);
mBtnShowFragmentA.setOnClickListener(this);
mBtnShowFragmentB.setOnClickListener(this);
mBtnGoAcitivity2.setOnClickListener(this);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
protected void addFragment(int contentId, Fragment fragment, boolean isAddStack,
String stackName) {
FragmentManager fm = getFragmentManager();
String newFragment = fragment.getClass().getName();
FragmentTransaction ft = fm.beginTransaction();
Fragment currentFragment = fm.findFragmentByTag(mCurrentFragmentTag);
if (currentFragment != null && !TextUtils.equals(currentFragment.getTag(), newFragment)) {
ft.hide(currentFragment);
}
if (fm.findFragmentByTag(newFragment) != null) {
fragment = (Fragment) fm.findFragmentByTag(newFragment);
}
if (!fragment.isAdded()) {
ft.add(contentId, fragment, newFragment);
} else {
ft.show(fragment);
}
if (isAddStack) {
ft.addToBackStack(stackName);
}
try {
ft.commitAllowingStateLoss();
} catch (Exception e) {
}
mCurrentFragmentTag = newFragment;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_show_fragmentA:
FragmentA fragmentA = new FragmentA();
addFragment(R.id.activity_main_content, fragmentA, false, null);
break;
case R.id.btn_show_fragmentB:
FragmentB fragmentB = new FragmentB();
addFragment(R.id.activity_main_content, fragmentB, false, null);
break;
case R.id.btn_go_activity2:
Intent intent = new Intent(getApplicationContext(), SettingActivity.class);
startActivity(intent);
break;
default:
break;
}
}
}
Fragment A
public class FragmentA extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_fragment_a, container, false);
return view;
}
}
Fragment B
public class FragmentB extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_fragment_b, container, false);
return view;
}
}
Activity 2
public class SettingActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_activity_2);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
}
...................
Use below code to remove activity from stack.
FragmentManager fragmentManager = getSupportFragmentManager();
if (fragmentManager .getBackStackEntryCount() > 0) {
fragmentManager .popBackStack();
}

Fragment setRetainInstance(true) not working

I have an Activity that contains a number of Fragments that are swapped based on the selected item in a Navigation Drawer. I am trying to retain the current fragment across an orientation change by calling setRetainInstance(true) on the Fragment and then checking if that fragment exists in onCreate(...). However, the Fragment is always null when I try to get it on onCreate(...). I've been banging my head against my desk for hours over this. Can anyone spot a problem?
Relevant parts of activity
public class StartActivity {
private static final String MAIN_FRAGMENT_TAG = "mainFragment";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
...
if(savedInstanceState != null) {
Fragment f = getSupportFragmentManager().findFragmentByTag(MAIN_FRAGMENT_TAG);
if(f == null) {
// FRAGMENT IS ALWAYS NULL
switchToModeForPosition(...);
} else {
setupActionBarForPosition(...);
}
} else {
// Default to events view
switchToModeForPosition(0);
}
}
private void switchToModeForPosition(int position) {
Fragment fragment;
switch (position) {
default:
case 0: //events
fragment = new EventsByWeekFragment();
setupActionBarForEvents();
break;
case 1: //teams
fragment = new AllTeamsListFragment();
setupActionBarForTeams();
break;
case 2: //insights
fragment = new InsightsFragment();
setupActionBarForInsights();
break;
case 3:
startActivity(new Intent(this, SettingsActivity.class));
mDrawerLayout.closeDrawer(mDrawerList);
return;
}
fragment.setRetainInstance(true);
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment, MAIN_FRAGMENT_TAG).commit();
}
}
use setRetainInstance(true)it in each Fragment class.
public void onCreated(Bundle savedInstanceState)
{
super.onCreated(savedInstanceState);
setRetainInstance(true);
}
Or
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
}

ActionBar Drop Down navigation - orientation change puts wrong fragment in

I am having a actionbar dropdown navigation. The problem is when I switch to a different fragment, then do an orientation change, it puts the first fragment inside anyways, even though I think I am handing savedInstanceState correctly. The problem seems to be that onNavigationItemSelected gets called, so .. how would I correctly handle this? I could make the savedInstanceState variable a field, but that just feels wrong...
public class MainActivity extends FragmentActivity implements MyListFragment.OnArticleSelectedListener {
public static final String TAG = "MainActivity";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState != null) {
Fragment savedFragment = getSupportFragmentManager().getFragment(savedInstanceState, "saved_fragment");
Log.d(MainActivity.TAG, "savedInstanceState != null: " + savedFragment.getTag());
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, savedFragment, savedFragment.getTag())
.commit();
} else {
Log.d(MainActivity.TAG, "savedInstanceState == null");
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, new MyListFragment(), MyListFragment.TAG)
.commit();
}
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
String[] array = new String[] { "Inzeráty", "Dummy frag" };
SpinnerAdapter mSpinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item,
array);
actionBar.setListNavigationCallbacks(mSpinnerAdapter, new ActionBar.OnNavigationListener() {
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
Log.d(MainActivity.TAG, "onNavitagionItemSelected");
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
switch(itemPosition) {
case 0:
transaction.replace(R.id.fragment_container, new MyListFragment(), MyListFragment.TAG);
break;
case 1:
transaction.replace(R.id.fragment_container, new MyDummyFragment(), MyDummyFragment.TAG);
break;
}
transaction.commit();
return true;
}
});
}
#Override
public void onArticleSelected(Bundle bundle) {
Log.d(MainActivity.TAG, "MainActivity # onArticleSelected");
Intent intent = new Intent(this, DetailActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
Log.d(MainActivity.TAG, "MainActivity # onSaveInstanceState: " + currentFragment.getTag());
getSupportFragmentManager().putFragment(outState, "saved_fragment", currentFragment);
super.onSaveInstanceState(outState);
}
}
I recently encountered this problem as well. I addressed it by overriding the onRetainCustomNonConfigurationInstance method on the activity.
#Override
public Object onRetainCustomNonConfigurationInstance() {
// return true so that onCreate will know it is an orientation change
return true;
}
In my onCreate I was then able to implement the following:
...
Object lastCustomNonConfigurationInstance = getLastCustomNonConfigurationInstance();
if (lastCustomNonConfigurationInstance != null) {
mIsOrientationChange = (Boolean) getLastCustomNonConfigurationInstance();
}
...
Lastly I updated onNavigationItemSelected so that it knew about mIsOrientationChange
#Override
public boolean onNavigationItemSelected(int position, long id) {
if (!mIsOrientationChange) {
// real navigation selected logic
}
mIsOrientationChange= false;
return true;
}
Edit: I got the idea to implement this from the following Android Developer article: http://developer.android.com/guide/topics/resources/runtime-changes.html#RetainingAnObject

Android: fragment restore after screen orientation change

I'm starting with fragments and I'm facing a problem. I wan't to restore my fragment after a screen rotation.
My app looks like this: on landscape I have a button on the left area, which updates the a label on the right area. If on portrait mode, I'm navigating to a new activity. However, I wan't to maintain the fragment state after rotating.
Code looks like this:
Left area fragment:
public class ListFragment extends Fragment implements OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list, container, false);
Button button = (Button) view.findViewById(R.id.button1);
button.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
updateDetail();
break;
}
}
public void updateDetail() {
String newTime = String.valueOf(System.currentTimeMillis());
DetailFragment fragment = (DetailFragment) getFragmentManager()
.findFragmentById(R.id.detailFragment);
if (fragment != null && fragment.isInLayout()) {
fragment.setText(newTime);
} else {
Intent intent = new Intent(getActivity().getApplicationContext(),
DetailActivity.class);
intent.putExtra("value", newTime);
startActivity(intent);
}
}
}
Right area activity:
public class DetailActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
finish();
return;
}
if (savedInstanceState == null) {
setContentView(R.layout.activity_detail);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String s = extras.getString("value");
TextView view = (TextView) findViewById(R.id.detailsText);
view.setText(s);
}
}
}
}
Right area fragment:
public class DetailFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater
.inflate(R.layout.fragment_detail, container, false);
return view;
}
public void setText(String item) {
TextView view = (TextView) getView().findViewById(R.id.detailsText);
view.setText(item);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
FragmentManager fm = getFragmentManager();
DetailFragment fragment = (DetailFragment)fm.findFragmentById(R.id.detailFragment);
if (fragment == null) {
fragment = new DetailFragment();
fragment.setTargetFragment(this, 0);
fm.beginTransaction().add(R.id.detailFragment, fragment).commit();
}
}
}
What can I possibly be doing wrong?
You have a few options you can use the Bundle in a couple of methods to save and restore the state of the fragments.
Or you can possibly use the setRetainInstance method:
onCreate(Bundle save)
{
super.onCreate(save);
setRetainInstance(true);
}
Keep in mind that the setRetainInstance method doesn't work for fragments in the backstack.
#Override
public void onConfigurationChanged(Configuration newConfig) {
int orientation = getResources().getConfiguration().orientation;
switch (orientation) {
case Configuration.ORIENTATION_LANDSCAPE:
getSupportFragmentManager().beginTransaction().replace(R.id.detailFragment, new DetailFragment()).commitAllowingStateLoss();
getSupportFragmentManager().beginTransaction().remove(new DetailFragment()).commitAllowingStateLoss();
break;
case Configuration.ORIENTATION_PORTRAIT:
getSupportFragmentManager().beginTransaction().replace(R.id.detailFragment, new DetailFragment()).commitAllowingStateLoss();
getSupportFragmentManager().beginTransaction().remove(new DetailFragment()).commitAllowingStateLoss();
break;
}
super.onConfigurationChanged(newConfig);
}
You can check on the onConfigurationChange and ensure that your fragment state is not lost by doing a commitAllowingStateLoss

Categories

Resources