Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android fragments vs compound controls

Why should Android 3.0 fragments be used instead of compound controls? One can create a View inheritor or compound control once and use it everywhere.

I've read http://android-developers.blogspot.com/2011/02/android-30-fragments-api.html but did not find the answer.

like image 983
Anton Avatar asked Jun 02 '11 12:06

Anton


People also ask

Is it better to use fragments or activities?

Activities are an ideal place to put global elements around your app's user interface, such as a navigation drawer. Conversely, fragments are better suited to define and manage the UI of a single screen or portion of a screen. Consider an app that responds to various screen sizes.

Are fragments still used in Android?

A Fragment is a combination of an XML layout file and a java class much like an Activity . Using the support library, fragments are supported back to all relevant Android versions.

Are fragments faster than activities?

Each tab will have a fragment to hold the products. The tabs could either held in activity or a fragment. I do find fragments a slightly faster than activities but really its not something you would really notice in most cases. Regardless if they was intended for speed or not they still seem/feel little quicker.


2 Answers

The difference is that fragments have a life cycle (onPause, onCreate, onStart...) of their own. By having a life cycle, fragments can respond independently to events, save their state through onSaveInstanceState, and be brought back (i.e. such as when resuming after an incoming call or when the user clicks the back button). The life cycle is summarized in the fragment documentation:

https://developer.android.com/guide/components/fragments.html#Lifecycle

You can always wrap a fragment or activity around a compound view, so just think of fragments as containers to your compound views that give them an independent life cycle.

like image 101
Henry Avatar answered Sep 30 '22 12:09

Henry


The reason would be to have the same code work on tablets and phones. There are different layout considerations for these devices and Fragments allow you to take that into consideration and have your app behave differently without having to rewrite any code.

like image 36
CaseyB Avatar answered Sep 30 '22 11:09

CaseyB