如何跨片段事务保存片段状态

时间:2012-04-12 02:30:16

标签: android android-fragments android-ui

我在围绕安卓片段缠绕时遇到了一些困难。我有ActionBar Spinner,我在每次点击旋转项目时都会创建一个新的Fragment。我有类似下面的代码:

public class MyActivity extends Activity
{
   ...  
   ...
   private void initActionBarSpinner()
   {
      getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

      OnNavigationListener callback = new OnNavigationListener()
      {
          @Override
          public boolean onNavigationItemSelected(int itemPosition, long itemId)
          {
             if (itemPosition >= 0 && itemPosition < dataSet.size())
             {
                openTagFragment(itemPosition);
                return true;
             }

             return false;
          }
       };

       spinnerAdapter = new ArrayAdapter<String>(this, R.layout.action_bar_spinner, R.id.spinnertAdapterItem, tags);
       getActionBar().setListNavigationCallbacks(spinnerAdapter, callback);
   }

   @Override
   public void onCreate(Bundle savedInstanceState)
   {
      Log.d(TAG, TAG + " oncreate");

      super.onCreate(savedInstanceState);

      initActionBarSpinnerAdapter();
   }

   protected void openTagFragment(int itemPosition)
   {
      Log.d(TAG, "Replacing fragment");

      String fragmentTag = dataSet.get(itemPosition);
      MyFragment myFragment = new MyFragment();
      myFragment.setData(dataSet.get(itemPosition));
      FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
      fragmentTransaction.replace(R.id.fragmentContainer, myFragment, fragmentTag);
      fragmentTransaction.addToBackStack(null);
      fragmentTransaction.commit();
   }
}

我面临的问题:在方向更改时,会创建一个新片段,这意味着它会再次从服务器获取相同的数据。我可以看到onSaveInstanceState()在旋转时调用现有片段,但如果我要再次对Fragment进行新操作,何时以及如何在片段onCreate()上获得有效的savedInstance包?

0 个答案:

没有答案