Golan Shay
Golan Shay

Reputation: 1270

Android Fragments and Activities

referring at the diagram below:

http://developer.android.com/guide/components/fragments.html

Could someone please please explain why Google suggests to use 2 separate activities on a Phone and a single activity on a Tablet? If I have code in activity A to manage Fragment B (for a Tablet) why should I repeat the same code in Activity B for a phone?

It seems that for a Phone I can still use 1 activity as well (only activity A) and replace fragments, this could reduce redundant code?

Thanks.

Upvotes: 2

Views: 646

Answers (3)

CoatedMoose
CoatedMoose

Reputation: 4228

Rejinderi's solution should work. I think that either that implementation or the one from Google's example can be a reasonable choice. It depends on what you are trying to achieve.

Personally, I prefer Google's example for the following reasons:

  1. Separate activities means you use the activity back stack. In some (most?) cases, the fragment back stack is fine, but the default transition is different. You may prefer one over the other for UX reasons.
  2. If you want to capture an intent, it may be unclear why ActivityA is capturing JobB.
  3. In my experience, the logic for handling FragmentB without FragmentA is (a bit) different, and breaking it into it's own activity helps separate that logic, and makes everything more readable.
  4. Menu options may also change. Again I find the separation of logic more clear.

Upvotes: 0

Rejinderi
Rejinderi

Reputation: 11844

I get what you mean..

You could use a fragment container and replace the fragments, define interface for selection callback. Google just does it this way maybe its clearer for those who come from the activities world i guess.

Upvotes: 1

Avner Shahar-Kashtan
Avner Shahar-Kashtan

Reputation: 14700

The reason is, essentially, that phones are small. Really small. Tiny, in fact.

Take the classic scenario of an email application. The two fragments in that scenario would be the Message List (Fragment A) and Message Content (Fragment B). On a tablet, where you've got space, you can combine them into a single activity, concurrently on screen, comfortably. On a phone, however, you need to carefully manage your screen real estate, so you should split them into the choose-a-message phase (Activity A showing Fragment A) and the read-a-message phase (Activity B showing Fragment B).

By developing them as fragments, similar to user controls in other platforms, you can use the same fragments in the same codebase on a tablet and a phone, composing the activity from existing fragments.

Upvotes: 3

Related Questions