Home > Blogs > Ask Big Nerd Ranch: Why do Fragments Matter in Android Application Development?

Ask Big Nerd Ranch: Why do Fragments Matter in Android Application Development?

By  Aug 13, 2013

Topics: Programming

The experts at Big Nerd Ranch answer the question, "Why do fragments matter in Android application development when you can develop apps without using them?"

Q: Why does your book Android Programming heavily advocate the use of fragments when developing Android applications? You can develop Android applications without using any fragments, so why bother? Why do fragments matter?

A: As Android developers, we have two main controller classes available to us: Activities and Fragments.

Activities have been around for a very long time and are used to construct a single screen of your application. When someone is using your Android application, the views that the user sees and interacts with are hosted and controlled by a single activity. Much of your code lives in these Activity classes, and there will typically be one activity visible on the screen at a time.

As an example, a simple activity may look like the following:

public class MainActivity extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}
}

When Honeycomb was released, the Fragment class was introduced. Fragments are another type of controller class that allows us to separate components of our applications into reusable pieces. Fragments must be hosted by an activity and an activity can host one or more fragments at a time.

A simple fragment looks similar to an activity, but has different life cycle callback methods. The fragment below accomplishes the same thing as the activity example above: it sets up a view.

public class MainFragment extends Fragment {
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			return inflater.inflate(R.layout.fragment_main, container, false);
	}
  
}

As you can see, activities and fragments look very similar and are both used to construct applications. So, what are the advantages that come with the use of Fragments?

Whoa, it looks like we’re running a bit long, so we’re going to try something new. Please click over to the Articles section of the site to read the rest of this tip.

Become an InformIT Member

Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.

Other Things You Might Like

Xamarin Unleashed

Xamarin Unleashed