Search code examples
androidandroid-tabhostrevert

Why doesn't the tabwidget remain modified?


In android I have an TabActivity (A) in which I create a single tab called loading with the Activity B.

From Activity B I modify the TabWidget from TabActivity A to add some more tabs via a static reference to the TabHost in TabActivity A.

After I start a new activity C and then press BACK the TabWidget has only one single tab called Loading.

I've tried in the onResume method of Activity B to recreate the tabs but it doesn't work anymore.

Does anyone know why does it do this and how can I fix it?


Solution

  • Relying on static variables pointing to UI components (like a TabHost) can lead to produce memory leaks. Don't do it. Instead register a BroadcastReceiver in the TabActivity to add new tabs. That way, instead of modifying a static variable, you send a broadcast (Context#sendBroadcast(Intent)) to tell the tab activity that you want a new tab.

    Also, make sure you save the state of the TabActivity, so that you can restore it if the Android OS destroys your activity for some reason. I recommend using the onRetainNonConfigurationInstance... something like this:

    private State mState;
    public void onCreate(Bundle b){
        // somewhere in onCreate
        mState = (State) getLastNonConfigurationInstance();
        if( mState == null ){
            mState = new State();
        } else {
            for(TabSpec tab : mState.tabs){
                //add them to the tab host
            }
        }
    }
    @Override
    public Object onRetainNonConfigurationInstance() {
        return mState;
    }
    
    private static class State{
        List<TabSpec> tabs;
        // more stuff that you want to save
    }