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
片段和開關內的一些文本框標籤之間強制應用程序丟失我添加到這些文本框的任何數據。取而代之的add
和remove
,我想用attach
和detach
節省了片段狀態。
如何完成的代碼中,我已經有了?
更新:
現在,該代碼如下所示:
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
我在這裏給出的解決方案與http://stackoverflow.com/questions/16634247/save-fragment-state-inside-a-tab完全相同。有什麼不同? – loadedion
我在插入代碼和預定義代碼之間的變量時遇到了一些麻煩:/ – Si8
您是否使用它?我想你錯過這裏的關鍵部分是,當你'ft.add標籤(viewID,片段,TAG)' – loadedion