Robert
Robert

Reputation: 1192

When to use and when not to use fragments in Android?

I am new in Android and I want to make an app, so, I was seeing a lot of tutorials and a few of them said that I need to use fragment, but in others tutorials say that if I want or only when my app is for Tablets. So, I really get me confuse about this, when I have to use fragment and when I not.

Please, explain to me when to use fragments or when not. thanks

Upvotes: 3

Views: 1613

Answers (2)

The One
The One

Reputation: 1085

For me I always use fragments in the sense that I can reuse it and my program will be compatible with a phone or a tablet.

But this answer is from Dummies for android development.

Knowing when to use activities or fragments

Both activities and fragments are central parts of your user interface (UI) code. So how then do you decide whether to put certain functionality into a fragment or an activity? If activities are the lunchbox of UI code, fragments are its Tupperware. You can insert your UI code directly into your lunchbox, but it would be a bit of a mess and make the lunchbox code hard to reuse. Put your UI code into your fragment Tupperware instead, where you can shift it from lunchbox to lunchbox as you need to use it again. If you’re absolutely certain that the code you’re writing is specific to a given activity, put it directly into an activity. But it you’re unsure, put your UI code in a fragment. In most applications, fragments contain all your UI code, and your activities contain only the glue that binds the fragments together.

Upvotes: 7

Caner
Caner

Reputation: 59148

A fragment is an independent component which can be used by an activity. A fragment encapsulate functionality so that it is easier to reuse within activities and layouts.

http://www.vogella.com/articles/AndroidFragments/article.html#fragments

but in others tutorials say that if I want or only when my app is for Tablets

Those tutorials you mentioned probably meant this:

Fragments make it easy to reuse components in different layouts, e.g. you can build single-pane layouts for handsets (phones) and multi-pane layouts for tablets. This is not limited to tablets; for example you can use fragments also to support different layout for landscape and portrait orientation on a smartphone.

http://www.vogella.com/articles/AndroidFragments/article.html#fragments_usage

When there is a big screen you don't want to leave empty space. When the screen is too small you don't want squeeze everything. The solution is to have 2 different layouts reusing as much code as possible. That is when Fragments are especially handy.

Upvotes: 2

Related Questions