Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use fragment in Android?

For very long time, I think what is the reason of using fragment in Android if I just develop the application for Android Phone only but not 10.1.

Is it necessary to use fragment? Also, what is the usage of fragment, I found that it may use for 'tab' and 'separate view'...

I really think it is very confusing. Can anyone explain briefly and give example?

like image 562
jjLin Avatar asked Dec 07 '12 04:12

jjLin


People also ask

What is the advantage of using fragments?

The Fragment class in Android is used to build dynamic User Interfaces and should be used within the activity. The biggest advantage of using fragments is that it simplifies the task of creating UI for multiple screen sizes. An activity can contain any number of fragments.

Why we should use fragment instead of activity?

After using multiple fragments in a single activity, we can create a multi-screen UI. Fragment cannot be used without an Activity. While Using fragments in the project, the project structure will be good and we can handle it easily. Lifecycle methods are hosted by OS.

Are fragments still used in Android?

Using the support library, fragments are supported back to all relevant Android versions. Fragments encapsulate views and logic so that it is easier to reuse within activities.


1 Answers

From documentation

You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).

Some advantages are..

  1. A particular UI part, once done in fragment, can be reused in same/different activities.
  2. You can separate different sections of UI, hence code will be neat, and easy readable.

The ability of fragment to be able to reuse is very helpful when you are creating applications for different kind of android devices (phones, tablets). A well designed fragment can be just plugged into your UI hierarchy.

like image 152
Krishnabhadra Avatar answered Dec 07 '22 20:12

Krishnabhadra