androidandroid-layoutandroid-fragmentsandroid-activityandroid-3.0-honeycomb

Why fragments, and when to use fragments instead of activities?


In Android API 11+, Google has released a new class called Fragment.

In the videos, Google suggests that whenever possible (link1, link2), we should use fragments instead of activities, but they didn't explain exactly why.

What's the purpose of fragments and some possible uses of them (other than some UI examples that can be easily be achieved by simple views/layouts)?

My question is about fragments:

  1. What are the purposes of using a fragment?
  2. What are the advantages and disadvantages of using fragments compared to using activities/views/layouts?

Bonus questions:

  1. Can you give some really interesting uses for fragments? Things that Google didn't mention in their videos?
  2. What's the best way to communicate between fragments and the activities that contain them?
  3. What are the most important things to remember when you use fragments? Any tips and warnings from your experience?

Solution

  • #1 & #2 what are the purposes of using a fragment & what are the advantages and disadvantages of using fragments compared to using activities/views/layouts?

    Fragments are Android's solution to creating reusable user interfaces. You can achieve some of the same things using activities and layouts (for example by using includes). However; fragments are wired in to the Android API, from HoneyComb, and up. Let me elaborate;

    Bonus 2

    The best way to communicate between fragments are intents. When you press something in a Fragment you would typically call StartActivity() with data on it. The intent is passed on to all fragments of the activity you launch.