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片段中有一些文本框,并且在选项卡之间切换会强制应用程序丢失我添加到这些文本框中的任何数据。而不是addand remove,我想使用attachanddetach来保存片段状态。

我如何在已有的代码中实现这一点?

更新

代码现在如下所示:

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
4

1 回答 1

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();
}
于 2013-07-31T19:09:16.500 回答