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

前端 未结 3 453
时光说笑
时光说笑 2021-02-04 01:54

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
3条回答
  •  没有蜡笔的小新
    2021-02-04 02:18

    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!

提交回复
热议问题