Why using Fragments?

后端 未结 3 1053
我在风中等你
我在风中等你 2021-02-09 13:22

I have read the documentation and some other questions\' threads about this topic and I don\'t really feel convinced; I don\'t see clearly the limits of use of this tech

相关标签:
3条回答
  • 2021-02-09 14:09

    Its quite a general question and not directly related to a specific programming problem. But in my opinion good software is based on good design and therefore a good understanding and best practices. So your question is a good one for stackoverflow.

    So, what about fragments. It took me a while to understand why you could or even should use them. As @pskink said, you can easily live without them. But if you are planning to rollout your software on different devices, you should definately think about fragments.

    The screen resolution and density is not the only problem. Think about a smartphone. The screen is much smaller, so you can not present your app the same way as you can on a tablet. For instance a master detail flow. Left side, a list of elements and when you click one element, you will see details of that element on the right side. Easy to do on a tablet. But on a smartphone you would put the master-view into one fragment and the detail-view into another one.

    You got two options to realize that scenario. Either programm different activities for smartphone and tablet but because they are actually doing the same logic, it's better practice to put the logic into fragments and reuse those fragments in two layouts (phone/tablet).

    0 讨论(0)
  • 2021-02-09 14:16

    If there's a certain positive aspect apart from the simpler reuse of logic through different layouts, it's the ability of Fragments to be kept alive by the system at orientation change, aka while an Activity is reconstructed from zero, a Fragment can retain its instance, and therefore using them is more stable than an Activity. Also, switching between Fragments is quicker.

    Personally, if I don't need to mess around with different orientations and layout sizes, I still prefer using Fragments and a singular container Activity around it, for stability and seamless switching between the different screens.

    0 讨论(0)
  • 2021-02-09 14:17

    You shouldn't always use fragments. Fragments have their uses, such as when you want to page in and out parts of the screen or when you want to drastically change the UI in different orientations. When they make sense, use them. When they don't, skip them. I find they make sense in maybe about 10-20% of apps- I rarely see the need.

    0 讨论(0)
提交回复
热议问题