Search code examples
javaandroidactionbarsherlock

class life cycle with ActionBar Sherlock Tab fragments


I'm working on one of my first Android applications and got stuck with the understanding of how controllers/classes lifecycle are arranged. I'm coming from an iOS background.

Basicly what I did was following this simple tutorial

So from what I understand I bind a TabListener to the Fragment. When switching tabs the TabListener's onTabSelected() gets called and each time a new instance of FragmentA/Fragment B is created.

That leads to the fact that every time I switch tabs all onCreate..() methods are called again.

I don't want to create a new fragment instance every time I switch tabs but rather use the one which was created intially at application start.

The question is how can I switch tabs without killing the fragments in there?


Solution

  • You can achieve this by just attaching/detaching the fragments, on your tab listener every time a tab is unselected detach the current fragment and on your onTabSelected method check if you have created the fragment before.

    private Fragment       mFragment;
    private final String   mTag;
    private final Class<T> mClass;
    
    public TabListener(String pTag, Class<T> pClass) {
        mTag = pTag;
        mClass = pClass;
    }
    
    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        if ( mFragment == null ) {
            try {
                mFragment = (Fragment)mClass.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            ft.add(R.id.fragment_container,mFragment,mTag);
        } else {
            ft.attach(mFragment);
        }   
    }
    
    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    
        if ( mFragment != null ) {
            ft.detach(mFragment);
        }
    }
    
       public void onTabReselected(Tab tab, FragmentTransaction ft) {
        //Nothing   
       }
    

    Then you can instantiate your listener as in

    TabListener l = new TabListener<MyFragment>(tabTag, MyFragment.class)