2013-07-31 46 views
0

我爲ActionBar以下代碼:如何附加()和分離()而不是添加()和刪除()以保存片段視圖

private class MyTabListener implements ActionBar.TabListener 
{ 
    private Fragment mFragment; 
    private final Activity mActivity; 
    private final String mFrag; 

    public MyTabListener(Activity activity, String fragName) 
    { 
     mActivity = activity; 
     mFrag = fragName; 
    } 

    @Override 
    public void onTabReselected(Tab tab, FragmentTransaction ft) 
    { 
     // TODO Auto-generated method stub 

    } 

    @Override 
    public void onTabSelected(Tab tab, FragmentTransaction ft) 
    { 
     mFragment = Fragment.instantiate(mActivity, mFrag); 
     ft.add(android.R.id.content, mFragment); 
    } 

    @Override 
    public void onTabUnselected(Tab tab, FragmentTransaction ft) 
    { 
     ft.remove(mFragment); 
     mFragment = null; 
    } 
} 

我有那些Tab片段和開關內的一些文本框標籤之間強制應用程序丟失我添加到這些文本框的任何數據。取而代之的addremove,我想用attachdetach節省了片段狀態。

如何完成的代碼中,我已經有了?

更新

現在,該代碼如下所示:

private class MyTabListener implements ActionBar.TabListener 
{ 
    private Fragment mFragment; 
    private final Activity mActivity; 
    private final String mFrag; 

    public MyTabListener(Activity activity, String fragName) 
    { 
     mActivity = activity; 
     mFrag = fragName; 
    } 

    @Override 
    public void onTabReselected(Tab tab, FragmentTransaction ft) 
    { 
     // TODO Auto-generated method stub 

    } 

    @Override 
    public void onTabSelected(Tab tab, FragmentTransaction ft) 
    { 
     //mFragment = Fragment.instantiate(mActivity, mFrag); 
     //ft.add(android.R.id.content, mFragment); 
      mFragment = mActivity.getSupportFragmentManager().findFragmentByTag(mFrag); 
      if(mFragment == null) { 
      mFragment = Fragment.instantiate(mActivity, mClass.getName()); 
      ft.add(android.R.id.content, mFragment, mFrag); 
      } else { 
      ft.attach(mFragment); 
      } 
    } 

    @Override 
    public void onTabUnselected(Tab tab, FragmentTransaction ft) 
    { 
     //ft.remove(mFragment); 
     //mFragment = null; 
      if (mFragment != null) { 
       ft.detach(mFragment); 
       } 
    } 
} 

而且我得到一個錯誤的下面一行:

mFragment = mActivity.getSupportFragmentManager().findFragmentByTag(mFrag); 

錯誤:

The method getSupportFragmentManager() is undefined for the type Activity 
+1

我在這裏給出的解決方案與http://stackoverflow.com/questions/16634247/save-fragment-state-inside-a-tab完全相同。有什麼不同? – loadedion

+0

我在插入代碼和預定義代碼之間的變量時遇到了一些麻煩:/ – Si8

+0

您是否使用它?我想你錯過這裏的關鍵部分是,當你'ft.add標籤(viewID,片段,TAG)' – loadedion

回答

1

而不是重寫代碼,您可以使用SharedPreferences臨時存儲正在顯示的變量。

在你離開的標籤的onDestroy方法,只需添加您的變量的喜好,並檢索它們,當你重新輸入標籤。

@Override 
public void onDestroy(){ 
    super.onDestroy(); 
    Log.i("OnDestroy", "Logged"); 
    SharedPreferences prefs = getActivity().getSharedPreferences("name", Context.MODE_PRIVATE); 
    Editor editor = prefs.edit(); 
    editor.putString("stringName", stringToStore); 
    editor.commit(); 
} 
+0

謝謝!這可以解決。 – Si8

相關問題