Building flexible UI using Fragments in Android SDK

Posted By : Arpit Sharma | 11-Jan-2013

fragments in android SDK

Today I will blog on how to build flexible UI using fragments in Android SDK. Fragments were introduced to attain more dynamic and flexible UI  designs from API level 11+.

Fragments are components which run in the context of an Activity. Fragment components encapsulate application code so that it is easier to reuse it and to support different sized devices.

Fragments are optional, you can use Views and ViewGroups directly in an Activity but in professional applications you should always use them.

 

Properties of Fragments :

  • It differs from an Activity. Fragments must exist within Activity.
  • Fragments have their own life cycle.
  • It may or may not contain any user interface.
  • These are flexible as they don't need to be paired with same activity each time. 
  • One can combine multiple fragments in a single Activity as per requirement.
  • Fragment's life cycle directly depends upon it's parent activity's life cycle.

 

Create and use Fragments :

Now, its time to create and use the fragment in project, i will explain each and every step of using fragment during the creation on a demo project.

1. Eclipse > File > New > Android Application Project.

2. Enter the following details in project .

  • Application Name : Fragment_Demo
  • Project Name : Fragment_Demo
  • Package Name : com.example.fragment_demo
  • Build SDK : Android 4.0 (API 14)
  • Minimum Required SDK : Android 3.0 (API 11)
  • Then Next > Next and Finish.

3. Create a class "StartFragment" which extends Fragment and override onCreateView method which returns its view. Avoid the error on R.layout.start_fragment for now.

 

package com.example.fragment_demo;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class StartFragment extends Fragment{

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.start_fragment, container, false);
	}

}

 

4. Similarly, create three more Fargment classes and name them Fragment1, Fragment2 and Fragment3.

5. Now its time to create android xml files for each fargment in layout foldar and name them start_fragment, fragment_1, fragment_2 and fragment_3.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="Select the Fragments"
        android:textSize="20dp"/>

</LinearLayout>

 

Follow this code for each fragments xml file(Please chnage the layout color and textView text for different xml).

6. Open main.xml and replace the existiing code from the given below.

 


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Fragment 1" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Fragment 2" />

        <Button
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Fragment 3" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/myFragment"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_weight="3">
    </LinearLayout>

</LinearLayout>

 

7. Open MainActivity.java, initialize Start_Fragment and Buttons.

 

package com.example.fragment_demo;

import android.os.Bundle;
import android.widget.Button;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;

public class MainActivity extends Activity {
	Button b1, b2, b3;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        FragmentManager fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        StartFragment sf = new StartFragment();
        ft.add(R.id.myFragment, sf);
        ft.commit();
        
        b1 = (Button) findViewById(R.id.button1);
        b2 = (Button) findViewById(R.id.button2);
        b3 = (Button) findViewById(R.id.button3);
    }
}

8. Now its time to defined action on buttons and replace the Fragment on click of button.

 

package com.example.fragment_demo;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;

public class MainActivity extends Activity {
	Button b1, b2, b3;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        FragmentManager fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        StartFragment sf = new StartFragment();
        ft.add(R.id.myFragment, sf);
        ft.commit();
        
        b1 = (Button) findViewById(R.id.button1);
        b2 = (Button) findViewById(R.id.button2);
        b3 = (Button) findViewById(R.id.button3);
        
        b1.setOnClickListener(onButtonClick);
        b2.setOnClickListener(onButtonClick);
        b3.setOnClickListener(onButtonClick);
    }
    Button.OnClickListener onButtonClick = new Button.OnClickListener(){
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Fragment fragment = null;
			if(v == b1){
				fragment = new Fragment1();
			}else if(v == b2){
				fragment = new Fragment2();
			}else if(v == b3){
				fragment = new Fragment3();
			}
			FragmentTransaction ft = getFragmentManager().beginTransaction();
			ft.replace(R.id.myFragment, fragment);
			ft.commit();
		}
    };
}

This is how you can use Fragments in Android, i hope this will help you.

 

 

Arpit Sharma

[email protected]

http://oodlestechnologies.com/

About Author

Author Image
Arpit Sharma

Arpit has been developing Android and iPhone applications for a while now and is expert in mobile application development . He excels in developing mobile applications with location based intelligence. Arpit loves Modelling as a hobby.

Request for Proposal

Name is required

Comment is required

Sending message..