Android: Fragments setup

Create a layout file as normal. But this time with a tag in it. It ‘name’ is a static public class we’ll shortly make.

	<?xml version=“1.0” encoding=“utf-8”?>
	<LinearLayout xmlns:android=“”
	    android:orientation=“vertical” >
	    <fragment android:name=”your.activity.namespace$OurFragment”
		    android:layout_height=“wrap_content” /> 

Then in your ‘Activity’ change its base class to FragmentActivity.

	public class OurExample extends FragmentActivity {

Now create a new public static class in this file. Note it has the same name (and be very careful you name it the same, lest badly title exceptions will come to haunt you) as the tag above.

	public static class OurFragment extends Fragment {
	     public View onCreateView(LayoutInflater inflater, ViewGroup container,
	     Bundle savedInstanceState) {    
		return inflater.inflate(R.layout.fraglayout, container, false);

Its one required method, onCreateView, will return a normal inflated layout file for its view. It has other lifecycle methods, which can be found in the docs.

android android-fragments

Edit on github
comments powered by Disqus
Click me