问题
I am currently using the Sherlock package and the view indicator package in my application to create a view pager with the titles at the top and then the action bar over that.
For the most part it works OK however I have noticed that invalidateOptionsMenu() stops working after a screen orientation change.
When my app loads it works fine until I rotate the device to landscape mode, from then on the invalidateOptionsMenu() call never invokes the onCreateOptionsMenu(Menu menu) method.
It's a simple OptionsMenu creation as follows:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add("About")
.setIcon(R.drawable.about)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add("Refresh")
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
return true;
}
Which is located in a SherlockFragmentActivity:
public class TestFragActivity extends SherlockFragmentActivity
I have three classes that extend the Fragment class:
OverviewFrag overviewFrag;
ForecastFrag forecastFrag;
LiveFrag liveFrag;
And I create them within the SherlockFragmentActivity like this:
overviewFrag = new OverviewFrag();
forecastFrag = new ForecastFrag();
liveFrag = new LiveFrag();
I then have a FragmentAdapter class as follows:
class TestFragmentAdapter extends FragmentPagerAdapter {
private int mCount = TAB_TITLES.length;
public TestFragmentAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return overviewFrag;
case 1:
return forecastFrag;
case 2:
return liveFrag;
default:
return null;
}
}
@Override
public int getCount() {
return mCount;
}
@Override
public CharSequence getPageTitle(int position) {
return TAB_TITLES[position];
}
}
The FrgamentPagerAdapter, ViewPAger and PageIndicator are set up in the onCreate as follows:
mAdapter = new TestFragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mPager.setOffscreenPageLimit(2);
mIndicator = (TitlePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
When the device is rotated I save the 3 Classes hat extend Fragment and return them in the onCreate like this:
overviewFrag = savedWeatherInstance.getSavedOverviewFrag();
forecastFrag = savedWeatherInstance.getSavedForecastFrag();
liveFrag = savedWeatherInstance.getSavedLiveFrag();
This is all I do, when I rotate the device I seen some strange behavior such as the invalidateOptionsMenu() method not working but also some strange behavior when I call methods in my classes that extend Fragment like this:
overviewFrag.refreshTask();
This seems to run the refreshTask() but Views don't seem to update correctly.
Can anyone help me as I am quite new to Fragments and I'm not sure I've handled their life cycle correctly here?
来源:https://stackoverflow.com/questions/13952083/android-how-to-handle-orientation-of-fragmentactivity