Rodrigo Rutsatz
Rodrigo Rutsatz

Reputation: 285

How and when to use Fragments in applications?

I am very in doubt of the structuring of my application. When to use Fragments is a big question for me still. I understand the concept of fragment, but I would like to know how more experienced programmers use them. Is it really only when there is a specific task the fragment should do? For instance, POP-UPs, what layout would be better used? And back to the fragments, do you usually have a skelleton fragment that can be used for more than one thing, and then reshape it to different final forms (minor changes) or would you just use different fragments if the layout changes?

Upvotes: 3

Views: 59

Answers (2)

Chris Stillwell
Chris Stillwell

Reputation: 10547

The most common way I use them is as a kind of plugin layout for my activities. Let's say I have several activities and all of them need to display an address, phone number and some buttons (call number, launch navigation/gps, etc). I pass the fragment the id and the fragment does the legwork of grabbing the information and populating fields for my activities. This way, if I need to add anything, say an email address, I just need to modify one section of code rather than each activity and layout file.

Upvotes: 1

tyczj
tyczj

Reputation: 73753

You should use fragments in a few situations but its going to depend on your app really.

If you have a layout that is going to be used in multiple places and the code is relatively the same, that is a very good candidate for a fragment so you can keep code down.

If you are making an app where the layout changes based on orientation or device type (tablet vs phone) then fragments are highly recommended to hold different layouts. It makes it easier to change or show multiple layouts if need be on a tablet.

I'm sure there are more scenarios but I would say these are the basics for fragment decision

Upvotes: 2

Related Questions