omarsafwany
omarsafwany

Reputation: 3821

Difference between Layout and Fragment Layout

When creating an new Android Activity, it used to create an xml file in the layouts folder where I would define the UI.Now it creats two files:

1.Layout file

2.Fragment Layout File.

Could someone explain the difference between the two? Also when trying to add items as listviews, buttons...etc. in which file should I add them to be called in my activity file.

Upvotes: 3

Views: 8002

Answers (3)

Frankline Kiplangat
Frankline Kiplangat

Reputation: 19

In short, before, it was an activity per its layout file, but now one activity could have more layouts, but the second layout file is automatically generated as a fragment to avoid collision while the android studio is matching the resources, similarly two or more activities could share the same fragment too.

Upvotes: 0

donfuxx
donfuxx

Reputation: 11321

The default structure of new Android projects has changed since a recent update of the adt:

  • How it is now: There will be a Fragment "PlaceHolderFragment" created which uses the fragments layout. The other layout is the one that the Activity uses.

  • How it was before: No Fragment was generated after creating a new project, so there was also no fragment layout needed.

==> You have to decide if you actually want to use Fragments now. If so use the fragment layout and learn how to use Fragments in Android. If you decide that you don't need to use Fragments for now, then you can just delete the PlaceHolderFragment code & delete the fragments layout.

Upvotes: 1

savanto
savanto

Reputation: 4550

Starting with Android 3.0, Activities may now host Fragments which can be used to develop portions of the UI, and be displayed in different configurations depending on screen size, orientation, and other factors. It is highly recommended to use Fragments in modern Android applications, but is not required.

You can create an Activity layout which will hold one or more Fragments, and then place your UI components in the Fragment's layout. The Activity will load the Fragment, and then the Fragment will inflate the layout you wish to present inside it. You can also dynamically add/remove/swap out different Fragments inside the same Activity, depending on what you wish to display to the user.

You can read more about how to use Fragments here: Fragments | Android Developers

You can also choose to ignore the Fragment design principle, and continue to place all of your layouts into the Activity layout file. In that case, you can delete the Fragment layout.

Upvotes: 5

Related Questions