Android,片段隐藏和显示

时间:2013-06-27 16:27:33

标签: android tabs android-fragments actionbarsherlock

public class MyTabListener <T extends SherlockFragment> implements TabListener{

private SherlockFragment mFragment;
private final SherlockFragmentActivity mActivity;
private final String mTag;
private final Class<T> mClass;

public MyTabListener(SherlockFragmentActivity mActivity, String mTag, Class<T> mClass) {

    this.mActivity = mActivity;
    this.mTag = mTag;
    this.mClass = mClass;
}

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {

    // Check if the fragment is already initialized
    if (mFragment == null) {
        // If not, instantiate and add it to the activity
        mFragment = (SherlockFragment) SherlockFragment.instantiate(
                mActivity, mClass.getName());

        ft.replace(android.R.id.content, mFragment, mTag);
    } else {
        // If it exists, simply attach it in order to show it
        ft.show(mFragment);
    }
}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {

    if (mFragment != null) {
        // Detach the fragment, because another one is being attached
        ft.hide(mFragment);
    }
}

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

}}

该代码隐藏了片段,但从未再次显示它们......任何建议??

1 个答案:

答案 0 :(得分:1)

我用replace()替换add()解决了这个问题,所以代码看起来像这样

public class MyTabListener <T extends SherlockFragment> implements TabListener{

private SherlockFragment mFragment;
private final SherlockFragmentActivity mActivity;
private final String mTag;
private final Class<T> mClass;

public MyTabListener(SherlockFragmentActivity mActivity, String mTag, Class<T> mClass) {

    this.mActivity = mActivity;
    this.mTag = mTag;
    this.mClass = mClass;
}

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {

    // Check if the fragment is already initialized
    if (mFragment == null) {
        // If not, instantiate and add it to the activity
        mFragment = (SherlockFragment) SherlockFragment.instantiate(
                mActivity, mClass.getName());

        ft.add(android.R.id.content, mFragment, mTag);
    } else {
        // If it exists, simply attach it in order to show it
        ft.show(mFragment);
    }
}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {

    if (mFragment != null) {
        // Detach the fragment, because another one is being attached
        ft.hide(mFragment);
    }
}

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

}}