Fragments - Do you have to use an Activity Wrapper around a fragment which comprises the whole Activity?

Graeme picture Graeme · Jul 13, 2011 · Viewed 11.8k times · Source

Consider the sample app from developers.android.com

This describes using Fragments like so:

  • On a Phone you can use Fragment 1 on Activity A and fragment 2 on Activity B.
  • On a tablet you have more real estate so you use Fragment 1 and Fragment 2 on Activity A.

Great! ... But... On the first example (the one with a phone) you create an Activity with an xml file containing a single <fragment> and that's all, in the activity you only call setContentView() on that xml? That seems like a lot of redundant code (Activity, XML & Fragment to display a Fragment): Can you set a Fragment as an Activity or is a Wrapper with XML always required?

Answer

Graeme picture Graeme · Jul 13, 2011

Ah, found it here

public class MainMenuHolder extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        // If not already added to the Fragment manager add it. If you don't do this a new Fragment will be added every time this method is called (Such as on orientation change)
        if(savedInstanceState == null)
            getSupportFragmentManager().beginTransaction().add(android.R.id.content, new MainMenuFragment()).commit();
    }
}

FragmentActivity allow's you to set the Fragment as the content of android.R.id.content which I assume is the android internal ID of the trunk view.

With this method you still end up with an mostly redundant activity (If all you want is the Fragment acting as the Activity). But still, half as much fluff as having an activity and an XML file acting as a container.

Any other answers would be appreciated!