使用ActionBar旋转Android的双重碎片

我用一个ActionBar做了一个简单的Android Activity来切换2个片段。 一切都好,直到我旋转设备。 事实上,当我旋转的时候,我有两个片段,一个是上一个活动的,另一个是第一个。 为什么? 如果旋转破坏并重新创build我的活动,为什么我获得2个片段?

示例代码:

活动

package rb.rfrag.namespace; import android.app.ActionBar; import android.app.ActionBar.Tab; import android.app.Activity; import android.os.Bundle; public class RFragActivity extends Activity { /** Called when the activity is first created. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Notice that setContentView() is not used, because we use the root // android.R.id.content as the container for each fragment // setup action bar for tabs final ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); //actionBar.setDisplayShowTitleEnabled(false); Tab tab; tab = actionBar.newTab() .setText(R.string.VarsTab) .setTabListener(new TabListener<VarValues>( this, "VarValues", VarValues.class)); actionBar.addTab(tab); tab = actionBar.newTab() .setText(R.string.SecTab) .setTabListener(new TabListener<SecFrag>( this, "SecFrag", SecFrag.class)); actionBar.addTab(tab); } } 

TabListener

 package rb.rfrag.namespace; import android.app.ActionBar; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.app.ActionBar.Tab; public class TabListener<T extends Fragment> implements ActionBar.TabListener { private Fragment mFragment; private final Activity mActivity; private final String mTag; private final Class<T> mClass; /** Constructor used each time a new tab is created. * @param activity The host Activity, used to instantiate the fragment * @param tag The identifier tag for the fragment * @param clz The fragment's Class, used to instantiate the fragment */ public TabListener(Activity activity, String tag, Class<T> clz) { mActivity = activity; mTag = tag; mClass = clz; } /* The following are each of the ActionBar.TabListener callbacks */ public void onTabSelected(Tab tab, FragmentTransaction ft) { // Check if the fragment is already initialized if (mFragment == null) { // If not, instantiate and add it to the activity mFragment = Fragment.instantiate(mActivity, mClass.getName()); ft.add(android.R.id.content, mFragment, mTag); } else { // If it exists, simply attach it in order to show it ft.attach(mFragment); } } public void onTabUnselected(Tab tab, FragmentTransaction ft) { if (mFragment != null) { // Detach the fragment, because another one is being attached ft.detach(mFragment); } } } 

Solutions Collecting From Web of "使用ActionBar旋转Android的双重碎片"

我已经解决了在Activity中使用onSaveInstanceStateonRestoreInstanceState来维护选定的选项卡并修改onTabSelected ,如下所示。

最后的修改避免了Android重build它不脱身的片段。 不过,我不明白为什么活动是由旋转事件破坏,而目前的片段没有。 (你有这个想法吗?)

 public void onTabSelected(Tab tab, FragmentTransaction ft) { // previous Fragment management Fragment prevFragment; FragmentManager fm = mActivity.getFragmentManager(); prevFragment = fm.findFragmentByTag(mTag); if (prevFragment != null) { mFragment = prevFragment; } // \previous Fragment management // Check if the fragment is already initialized if (mFragment == null) { // If not, instantiate and add it to the activity mFragment = Fragment.instantiate(mActivity, mClass.getName()); ft.add(android.R.id.content, mFragment, mTag); } else { // If it exists, simply attach it in order to show it ft.attach(mFragment); } } 

由于我使用android.support.v4.view.ViewPager覆盖onTabSelected没有帮助。 但是你的暗示仍然指向了正确的方向。

android.support.v4.app.FragmentManager将所有片段保存在android.support.v4.app.FragmentActivityonSaveInstanceState中。 忽略setRetainInstance – 根据您的devise,这可能会导致重复的碎片。

最简单的解决方法是删除活动的orCreate中保存的片段:

  @Override public void onCreate (final android.os.Bundle savedInstanceState) { if (savedInstanceState != null) { savedInstanceState.remove ("android:support:fragments"); } // if super.onCreate (savedInstanceState); … return; } // onCreate 

该解决scheme实际上并不需要大量的工作,下面的步骤确保在旋转屏幕时保持选项卡select。 我遇到了重叠片段,因为在屏幕旋转时我的第一个选项卡被选中,而不是在旋转屏幕之前select的第二个选项卡,因此第一个选项卡与第二个选项卡的内容重叠。

这是你的活动应该看起来(我使用ActionBarSherlock,但调整它应该很容易):

 public class TabHostActivity extends SherlockFragmentActivity { private static final String SELETED_TAB_INDEX = "tabIndex"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Setup the action bar ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Create the Tabs you need and add them to the actionBar... if (savedInstanceState != null) { // Select the tab that was selected before orientation change int index = savedInstanceState.getInt(SELETED_TAB_INDEX); actionBar.setSelectedNavigationItem(index); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // Save the index of the currently selected tab outState.putInt(SELETED_TAB_INDEX, getSupportActionBar().getSelectedTab().getPosition()); } } 

这就是我的ActionBar.TabListener的外观(它是上面的Activity中的一个私有类):

  private class MyTabsListener<T extends Fragment> implements ActionBar.TabListener { private Fragment fragment; private final SherlockFragmentActivity host; private final Class<Fragment> type; private String tag; public MyTabsListener(SherlockFragmentActivity parent, String tag, Class type) { this.host = parent; this.tag = tag; this.type = type; } @Override public void onTabSelected(Tab tab, FragmentTransaction transaction) { /* * The fragment which has been added to this listener may have been * replaced (can be the case for lists when drilling down), but if the * tag has been retained, we should find the actual fragment that was * showing in this tab before the user switched to another. */ Fragment currentlyShowing = host.getSupportFragmentManager().findFragmentByTag(tag); // Check if the fragment is already initialised if (currentlyShowing == null) { // If not, instantiate and add it to the activity fragment = SherlockFragment.instantiate(host, type.getName()); transaction.add(android.R.id.content, fragment, tag); } else { // If it exists, simply attach it in order to show it transaction.attach(currentlyShowing); } } public void onTabUnselected(Tab tab, FragmentTransaction fragmentTransaction) { /* * The fragment which has been added to this listener may have been * replaced (can be the case for lists when drilling down), but if the * tag has been retained, we should find the actual fragment that's * currently active. */ Fragment currentlyShowing = host.getSupportFragmentManager().findFragmentByTag(tag); if (currentlyShowing != null) { // Detach the fragment, another tab has been selected fragmentTransaction.detach(currentlyShowing); } else if (this.fragment != null) { fragmentTransaction.detach(fragment); } } public void onTabReselected(Tab tab, FragmentTransaction fragmentTransaction) { // This tab is already selected } 

上面的实现也允许基于标签来replace标签内的片段。 为此,在同一选项卡中切换片段时,我使用相同的标签名称,用于已添加到选项卡的初始框架。

感谢Martin和asclepix提供他们的解决scheme。 我有3个选项卡,第一个选项卡包含2个片段,如下所示:

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" tools:context=".MainActivity" > <FrameLayout android:id="@+id/frActiveTask" android:layout_width="fill_parent" android:layout_height="50dp" android:layout_alignParentBottom="true" /> <FrameLayout android:id="@+id/frTaskList" android:layout_width="fill_parent" android:layout_height="match_parent" android:layout_alignParentTop="true" android:layout_above="@id/frActiveTask" /> </RelativeLayout> 

使用onRestoreInstanceStateonSaveInstanceStatesavedInstanceState.remove("android:support:fragments"); 方法和声明几乎可以正常工作,除非您的活动选项卡不是第一个,并且先旋转并单击,则会显示一个清晰的显示,只有第一个选项卡上的第二次点击才会显示右边的片段。 在debugging代码之后,我发现第一个addTab总是在tab监听器中调用一个onTabSelected事件,并使用fragment add方法,然后在onRestoreInstanceState调用setSelectedNavigationItem时,会在第一个选项卡上执行detach ,为另一个执行add 。 这个不必要的add电话是固定在我的解决scheme。

我的活动

 protected void onCreate(Bundle savedInstanceState) { boolean firstTabIsNotAdded = false; if (savedInstanceState != null) { savedInstanceState.remove("android:support:fragments"); firstTabIsNotAdded = savedInstanceState.getInt(SELETED_TAB_INDEX) != 0; } super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // codes before adding tabs actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); tabStartAndStop = actionBar.newTab().setText(getString(R.string.tab_title_start_and_stop)) .setTabListener( new FragmentTabListener<StartStopFragment>(this, getString(R.string.tab_title_start_and_stop_id), StartStopFragment.class, firstTabIsNotAdded)); tabHistory = actionBar.newTab().setText(getString(R.string.tab_title_history)) .setTabListener( new FragmentTabListener<HistoryFragment>(this, getString(R.string.tab_title_history_id), HistoryFragment.class, false)); tabRiporting = actionBar.newTab().setText(getString(R.string.tab_title_reporting)) .setTabListener( new FragmentTabListener<ReportingFragment>(this, getString(R.string.tab_title_reporting_id), ReportingFragment.class, false)); actionBar.addTab(tabStartAndStop); actionBar.addTab(tabHistory); actionBar.addTab(tabRiporting); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { if (savedInstanceState != null) { int index = savedInstanceState.getInt(SELETED_TAB_INDEX); actionBar.setSelectedNavigationItem(index); } super.onRestoreInstanceState(savedInstanceState); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // Save the index of the currently selected tab outState.putInt(SELETED_TAB_INDEX, getSupportActionBar().getSelectedTab().getPosition()); } 

而修改后的标签监听器

 public class FragmentTabListener<T extends SherlockFragment> implements com.actionbarsherlock.app.ActionBar.TabListener { private Fragment mFragment; private final Activity mFragmentActivity; private final String mTag; private final Class<T> mClass; private boolean doNotAdd; /** Constructor used each time a new tab is created. * @param activity The host Activity, used to instantiate the fragment * @param tag The identifier tag for the fragment * @param clz The fragment's Class, used to instantiate the fragment */ public FragmentTabListener(Activity activity, String tag, Class<T> clz, boolean doNotAdd) { mFragmentActivity = activity; mTag = tag; mClass = clz; this.doNotAdd = doNotAdd; } /* The following are each of the ActionBar.TabListener callbacks */ public void onTabSelected(Tab tab, FragmentTransaction ft) { // Check if the fragment is already initialized if (mFragment == null) { // If not, instantiate and add it to the activity if(doNotAdd){ doNotAdd = false; }else{ mFragment = Fragment.instantiate(mFragmentActivity, mClass.getName()); ft.add(android.R.id.content, mFragment, mTag); } } else { // If it exists, simply attach it in order to show it ft.attach(mFragment); } } public void onTabUnselected(Tab tab, FragmentTransaction ft) { if (mFragment != null) { // Detach the fragment, because another one is being attached ft.detach(mFragment); } } public void onTabReselected(Tab tab, FragmentTransaction ft) { // User selected the already selected tab. Usually do nothing. } }