What can be the difference of using a fragment and frameLayout in android? Can both be used interchangeably?

后端 未结 2 1397
误落风尘
误落风尘 2021-02-13 12:46

I have seen an approach where frameLayout is used in case of fragments. The ultimate goal was to have multiple fragments.

2条回答
  •  不知归路
    2021-02-13 13:14

    For showing a single Fragment immediately on the screen, yes, you can use fragment or FrameLayout interchangeably.

    Single Fragment, Method 1

    Showing the Fragment via the fragment tag would look like this in XML:

    
    

    Single Fragment, Method 2

    Showing the Fragment via FrameLayout would look like this in XML:

    
    

    Followed by Java code like this:

    Fragment newFragment = new ExampleFragment();
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.replace(R.id.details, newFragment);
    transaction.addToBackStack(null);
    transaction.commit();
    

    Multiple Fragments

    Method 2 then supports changing what fragment you are showing later by running more Java code to change what Fragment is there afterwards:

    Fragment secondFragment = new SecondExampleFragment();
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.replace(R.id.details, secondFragment);
    transaction.addToBackStack(null);
    transaction.commit();
    

    So FrameLayout gives you the extra ability to do that over using the fragment tag.

提交回复
热议问题