Why should I use fragment in Android?

2019-01-27 15:19发布

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?

3条回答
老娘就宠你
2楼-- · 2019-01-27 15:49

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.

查看更多
forever°为你锁心
3楼-- · 2019-01-27 16:02

Fragments is a new concept introduced in 3.0 version.

The basic purpose of fragments is:

  1. Fragments are designed to use the device UI space efficiently. When you are writing an application in android, then some people can download it into phone, some into tablets. If you see the space in tablets it will be little bigger than phones. You should be able to use that space efficiently. But you can't keep writing different applications one targeting for phone, and other targeting for tablets. In order to do it efficiently, i.e writing only application that can fit well with all screen sizes, we use fragments concept.

  2. fragments are designed as a reusable UI components between more than one activity. Once you design a fragment, you can view it as a detachable independent unit, so that you can plug it into any activity where ever there is a space. That means you can reuse the code designed for a fragment.

Fragment you can think of it like a sub activity, which sits with in an activity and which contributes its own UI to the activity screen. Fragments are always part of an activity. With out an activity, a fragment will not exist. So your fragment life cycle will always be affected by activity life cycle. An activity can contain more than one fragment. Similarly a fragment can be re used in multiple activities.

查看更多
做个烂人
4楼-- · 2019-01-27 16:11

If you use Fragment in your application, your apps will support all the device like small device, tablet and even google TV. In one .apk file, we will have different design for various devices.

This is the best Android tutorial that I've ever found. Section 21 covers fragments

Refer Here

查看更多
登录 后发表回答