Question

I am planning an app and trying to explore all the possible development options/methods I have available. One thing I'm struggling to get my head around is Fragments. I see a lot of people praising them as you can "resuse" fragments throughout the app but I can't think of an example situation.

From some example apps I have looked at (all been tabular layouts) the code for each fragment has one layout, so why not have a seperate activity instead?

I am hoping to implement a tabular layout in my app. If anyone can give me an example of a fragment being reused within an app I hope it will give me a better understanding of the benefits.

Was it helpful?

Solution

"Reuse" is overrated. Of course - you can put this same fragment (with this same features) in different places of your application - let's say that you can use a fragment in different, horizontal and vertical layouts (as you probably saw in Google's tutorial).

But at the end using fragments simplifies your project - for example - you can switch fragments inside one activity and get benefits of much easier navigation and in app communication.

Using fragments gives you one more thing - flexibility. It's much easier to move some view from one place to another, or just remove from application. All that because fragment encapsulates logic and usually a view, still offering power of externally managed lifecycle. (Thanks for comment from Richard Le Mesurier)

OTHER TIPS

Fragment is not a View neither a ViewGroup. It is not a visual element at all. Fragment inherits directly from Object.

One should think of a Fragment as a unity of a reusable code, reusable in various Activities (the Activities consist of visible elements).

Thus if you can think of any code you can reuse through several Activities (even the same Activity with different layout) and that code somehow depends on Activity lifecycle, then you probably should make this code a Fragment.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top