我有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
答案 0 :(得分: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();
}