我有以下代码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
and remove
,我想使用attach
anddetach
来保存片段状态。
我如何在已有的代码中实现这一点?
更新:
代码现在如下所示:
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