Switching fragments within tab

前端 未结 1 1515
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-02 16:22

I\'m creating an app that uses ActionBarSherlock. The app consists of three tabs, and in each of them, multiple screens are shown consecutively based on user input. I am abl

相关标签:
1条回答
  • 2020-12-02 16:45

    So what happened was that, in TabListener, in the onTabUnselected method, the Fragment was not detached, causing it to still be show while a new Fragment was shown.

    The cause to this was, that the Fragment that was detached was the first fragment, and not my second fragment. I've made some changes.

    In the Activity:

    SingleStationFragment singleStationFragment = new SingleStationFragment();
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(android.R.id.content, singleStationFragment, "STATIONS");
    transaction.addToBackStack(null);
    transaction.commit();
    

    Here I've added the "STATIONS" tag in the replace() method, which is the same tag as the first fragment.
    The TabListener is now as follows:

    public class TabListener<T extends SherlockFragment> implements com.actionbarsherlock.app.ActionBar.TabListener {
        private final SherlockFragmentActivity mActivity;
        private final String mTag;
        private final Class<T> mClass;
    
        private SherlockFragment mFragment;
    
        public TabListener(SherlockFragmentActivity activity, String tag, Class<T> clz) {
            mActivity = activity;
            mTag = tag;
            mClass = clz;
        }
    
        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            SherlockFragment preInitializedFragment = (SherlockFragment) mActivity.getSupportFragmentManager().findFragmentByTag(mTag);
            if (preInitializedFragment == null) {
                mFragment = (SherlockFragment) SherlockFragment.instantiate(mActivity, mClass.getName());
                ft.add(R.id.treinverkeer_fragmentcontent, mFragment, mTag);
            } else {
                ft.attach(preInitializedFragment);
            }
        }
    
        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            SherlockFragment preInitializedFragment = (SherlockFragment) mActivity.getSupportFragmentManager().findFragmentByTag(mTag);
    
            if (preInitializedFragment != null) {
                ft.detach(preInitializedFragment);
            } else if (mFragment != null) {
                ft.detach(mFragment);
            }
        }
    
        public void onTabReselected(Tab tab, FragmentTransaction ft) {
            // User selected the already selected tab. Usually do nothing.
        }
    }
    

    In the onTabUnselected method I now first retrieve the correct Fragment, then detach it.

    Hope this helps someone!

    0 讨论(0)
提交回复
热议问题