Pergunta

I'm creating an app with an actionBar with tabs. I would like it so that when you select a tab, a specific fragment is called. I have a problem where when the app is created, two fragments are immediately called when only one should be called. My code regarding that is as follows:

@Override
public Fragment getItem(int index)
{
    switch (index)
    {
        final String TAG0 = "MainActivity";
        Log.wtf(TAG0, "fragA active");
        case 0:
        return new FragA();

        final String TAG1 = "MainActivity";
        Log.wtf(TAG1, "fragB active");            
        case 1:
        return new fragB();

        final String TAG2 = "MainActivity";
        Log.wtf(TAG2, "fragC active");            
        case 2:
        return new fragC();
    }
    return null;
}

The actionBar's tabs are set up so that tabA opens fragA, tabB for fragB, etc. Now when the app is created, the log messages i'm getting show fragA active and fragB active although only tabA is selected. When tabB is selected, fragC becomes active. when tabC is selected, nothing happens. When you go to select any other tab after this, I'm getting no additional log messages.

The second situation is when the app starts, fragA and fragB are active although only tabA is selected. When you click tabC, fragC now becomes active. When you click any other tab after this, nothing happens and I receive no additional log messages.

Also, I think it's worth noting I've tried adding in break statements in each case within the switch statement. When I have a break statement for cases 0, 1, and 2, the break statements for cases 1 and 2 are fine, but the break statement for case 0 shows that is an unreachable statement.

If you need any additional code from me, please let me know. Thank you for your help.

Foi útil?

Solução

The Android ViewPager (which I assume you are using) always pre-loads the next tab for performance reasons. So you are on tab 1 and it knows you are likely to switch to tab 2 soon, so it pre-loads tab 2 in memory so that when you swipe, it is already ready to be displayed on screen. Otherwise there would be a tiny pause between when you start dragging and when the Fragment is ready to be shown on the screen. This is the intended behaviour and you cannot turn it off. You can increase the number of tabs it will preload, but the minimum is 1 either side.

Once you've viewed the tabs, they stay in memory unless the memory is exhausted. This is again so that the system doesn't have to recreate them. This is why you don't see the fragments being created a second time.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top