3

I am new to android and one thing I am very confused about is Fragment vs Activity. Everywhere now it is suggested that you should use Fragment instead of Activity.

So does it mean that I should make a single Activity and every UI element as Fragment and handle user actions through fragment transactions.

SO my doubt is do every application have single Activity nowdays? If no, why there is need for extra Activities.

Hope I am clear and sorry if it is already answered in some other way.

Thanks

user3265443
  • 535
  • 1
  • 8
  • 25
  • possible duplicate of [android - need some clarifications of fragments vs activities and views](http://stackoverflow.com/questions/10478233/android-need-some-clarifications-of-fragments-vs-activities-and-views) – user1140237 Feb 09 '15 at 05:48

1 Answers1

2

this question has already been asked. However, Fragment is a portion of UI. A fragment relies on an activity, which can handle as many fragments as needed.

I don't think that you absolutely have to limit yourself to having a single activity only. Though, that pattern (1 activity + N fragments) proved useful to me. In my app, a simple quiz game, each of the fragments capture user actions and trigger async activity calls by the means of callbacks.

Example:

  // Implements the main view of the app (home page)
  public class HomeFragment extends Fragment {

    /**
     * A pointer to the current callbacks instance (an Activity).
     */
    private HomeMenuCallbacks callbacks;

    /**
     * Callbacks interface (implemented by the Activity)
     */
    public static interface HomeMenuCallbacks {
        /**
         * Called when an item in the navigation drawer is selected.
         */
        void onHomeMenuItemSelected(int position);
    }    
}

public class MainActivity extends Activity implements
        HomeFragment.HomeMenuCallbacks {

    @Override
    public void onHomeMenuItemSelected(int position) {
      // Do whatever action based on which 
      // item from the home page menu was selected
    }
}

Check this thread for discussions and link to Android dev guide: Android - I need some clarifications of fragments vs activities and views

Community
  • 1
  • 1
Tomas Zezula
  • 220
  • 4
  • 7