Skip to main content

working with Fragments in android

Fragments are one of the most useful user interface components in android. Making of a very complex user interface made easy by using the fragments. We can easily categorize an android activity into separate modules using the fragment feature of android.
Ads by Google



 Why we use the fragment ?
We know that there are a lot of android devices with different screen resolutions are available on the market. So the making of an android app for a particular device or resolution is not practical. Fragments help us to solve this problem. We can categorize the UI of an activity using fragments. If the app open in a high resolution device then the detailed representation of the activity shown and if it is a standard definition device then the system shows only one or more fragment view of that activity.
android fragments tutorial

You can implement the Fragments in two ways
1. Insert the Fragment directly in to the XML file of an activity.
2. Insert the Fragment programatically to an activity.
While working with Fragments make sure that you select the minimum sdk version as Android 3.0 (API : 11)

How to insert a Fragment directly into the XML file of an android activity ?
Create a new android application project in eclipse IDE.
Step 1: Right click the layout folder and create a new android layout xml file and name it as fragment_layout.
fragment_layout.xml
1:  <?xml version="1.0" encoding="utf-8"?>  
2:  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
3:    android:layout_width="match_parent"  
4:    android:layout_height="match_parent"   
5:    android:background="#657578"  
6:    >  
7:    <TextView  
8:      android:id="@+id/textView1"  
9:      android:layout_width="wrap_content"  
10:      android:layout_height="wrap_content"  
11:      android:layout_alignParentTop="true"  
12:      android:layout_centerHorizontal="true"  
13:      android:layout_marginTop="141dp"  
14:      android:text="Welcome to first fragment"  
15:      android:textAppearance="?android:attr/textAppearanceLarge" />  
16:  </RelativeLayout>  

Step 2 : Right click the package and create a new java class with name FirstFragment. Extends that class with Fragment and make the override method onCreateView(). Now inflate the Fragment layout through the inflate() method and finally return view of the fragment.
FirstFragment.java
1:  package com.fragment1;  
2:  import android.app.Fragment;  
3:  import android.os.Bundle;  
4:  import android.view.LayoutInflater;  
5:  import android.view.View;  
6:  import android.view.ViewGroup;  
7:  public class FirstFragment extends Fragment {  
8:       @Override  
9:       public View onCreateView(LayoutInflater inflater, ViewGroup container,  
10:                 Bundle savedInstanceState) {  
11:            // TODO Auto-generated method stub  
12:            View v;  
13:            v = inflater.inflate(R.layout.fragment_layout, container,false);  
14:            return v;  
15:       }  
16:  }  

Step 3: Add the Fragment to the activity. In that Fragment the android:name indicates the Fragment class file.   
1:  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
2:    xmlns:tools="http://schemas.android.com/tools"  
3:    android:layout_width="match_parent"  
4:    android:layout_height="match_parent"  
5:    android:paddingBottom="@dimen/activity_vertical_margin"  
6:    android:paddingLeft="@dimen/activity_horizontal_margin"  
7:    android:paddingRight="@dimen/activity_horizontal_margin"  
8:    android:paddingTop="@dimen/activity_vertical_margin"  
9:    tools:context=".MainActivity"  
10:    android:background="#E0DDBD"  
11:     >  
12:    <TextView  
13:      android:id="@+id/textView1"  
14:      android:layout_width="wrap_content"  
15:      android:layout_height="wrap_content"  
16:      android:layout_alignParentLeft="true"  
17:      android:layout_alignParentTop="true"  
18:      android:layout_marginLeft="70dp"  
19:      android:text="Main Activity"  
20:      android:textAppearance="?android:attr/textAppearanceLarge" />  
21:    <fragment  
22:      android:id="@+id/fragment1"  
23:      android:name="com.fragment1.FirstFragment"  
24:      android:layout_width="wrap_content"  
25:      android:layout_height="match_parent"  
26:      android:layout_below="@+id/textView1"  
27:      android:layout_centerHorizontal="true"  
28:      android:layout_marginTop="31dp" />  
29:  </RelativeLayout>  
programatically add a fragment

Watch video of this topic

How to add Fragment Programatically to an Activity ?
Create a new android application project in eclipse. Create two fragments with layout names fragment_one and fragment_two and their corresponding  class names are FragmentOne and FragmentTwo.
Add a button on the activity_main.xml file. Also don't forget to add an id for activity_mail.xml file.
1:  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
2:    xmlns:tools="http://schemas.android.com/tools"  
3:    android:layout_width="match_parent"  
4:    android:layout_height="match_parent"  
5:    android:paddingBottom="@dimen/activity_vertical_margin"  
6:    android:paddingLeft="@dimen/activity_horizontal_margin"  
7:    android:paddingRight="@dimen/activity_horizontal_margin"  
8:    android:paddingTop="@dimen/activity_vertical_margin"  
9:    tools:context=".MainActivity"   
10:    android:id="@+id/main_id"  
11:    >  
12:    <TextView  
13:      android:id="@+id/textView1"  
14:      android:layout_width="wrap_content"  
15:      android:layout_height="wrap_content"  
16:      android:layout_alignParentTop="true"  
17:      android:layout_centerHorizontal="true"  
18:      android:text="Main Activity"  
19:      android:textAppearance="?android:attr/textAppearanceLarge" />  
20:    <Button  
21:      android:id="@+id/b1"  
22:      android:layout_width="wrap_content"  
23:      android:layout_height="wrap_content"  
24:      android:layout_below="@+id/textView1"  
25:      android:layout_centerHorizontal="true"  
26:      android:text="Show First Fragment" />  
27:  </RelativeLayout>  

For connecting a fragment to an activity you need to get an object of API FragmentTransaction. For getting the FragmentTransaction, you can use the object of FragmentManager class. add() method is used to add the fragment to the activity. You need to commit a transaction to take effect.   
1:  FragmentManager fm = getFragmentManager();  
2:  FragmentTransaction ft = fm.beginTransaction();  
3:  FragmentOne f1 = new FragmentOne();  
4:  ft.add(R.id.main_id, f1);  
5:  ft.commit();  

Add a button on the first fragment layout for open the second fragment  and don't forget to add an id for the first fragment layout.
fragment_one.xml
1:  <?xml version="1.0" encoding="utf-8"?>  
2:  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
3:    android:layout_width="match_parent"  
4:    android:layout_height="match_parent"  
5:    android:id="@+id/fr1_id"  
6:     >  
7:    <TextView  
8:      android:id="@+id/textView1"  
9:      android:layout_width="wrap_content"  
10:      android:layout_height="wrap_content"  
11:      android:layout_alignParentLeft="true"  
12:      android:layout_alignParentTop="true"  
13:      android:layout_marginLeft="91dp"  
14:      android:layout_marginTop="137dp"  
15:      android:text="First Fragment"  
16:      android:textAppearance="?android:attr/textAppearanceLarge" />  
17:    <Button  
18:      android:id="@+id/b2"  
19:      android:layout_width="wrap_content"  
20:      android:layout_height="wrap_content"  
21:      android:layout_below="@+id/textView1"  
22:      android:layout_centerHorizontal="true"  
23:      android:text="Show second Fragment" />  
24:  </RelativeLayout>  

MainActivity.java
1:  import android.app.Activity;  
2:  import android.app.FragmentManager;  
3:  import android.app.FragmentTransaction;  
4:  import android.os.Bundle;  
5:  import android.view.Menu;  
6:  import android.view.View;  
7:  import android.view.View.OnClickListener;  
8:  import android.widget.Button;  
9:  import android.widget.Toast;  
10:  public class MainActivity extends Activity {  
11:       Button bn;  
12:       @Override  
13:       protected void onCreate(Bundle savedInstanceState) {  
14:            super.onCreate(savedInstanceState);  
15:            setContentView(R.layout.activity_main);  
16:            bn = (Button)findViewById(R.id.b1);  
17:            bn.setOnClickListener(new OnClickListener() {  
18:                 @Override  
19:                 public void onClick(View v) {  
20:                      // TODO Auto-generated method stub  
21:                      FragmentManager fm = getFragmentManager();  
22:                      FragmentTransaction ft = fm.beginTransaction();  
23:                      FragmentOne f1 = new FragmentOne();  
24:                      ft.add(R.id.main_id, f1);  
25:                      ft.commit();  
26:                 }  
27:            });  
28:       }  
29:       @Override  
30:       public boolean onCreateOptionsMenu(Menu menu) {  
31:            // Inflate the menu; this adds items to the action bar if it is present.  
32:            getMenuInflater().inflate(R.menu.main, menu);  
33:            return true;  
34:       }  
35:  }  

Add the second fragment into the first fragment.
FragmentOne.java
1:  import android.app.FragmentTransaction;  
2:  import android.os.Bundle;  
3:  import android.view.LayoutInflater;  
4:  import android.view.View;  
5:  import android.view.View.OnClickListener;  
6:  import android.view.ViewGroup;  
7:  import android.widget.Button;  
8:  public class FragmentOne extends Fragment  
9:  {  
10:       Button bn;  
11:       @Override  
12:       public View onCreateView(LayoutInflater inflater, ViewGroup container,  
13:                 Bundle savedInstanceState) {  
14:            // TODO Auto-generated method stub  
15:            View v;  
16:            v = inflater.inflate(R.layout.fragment_one, container,false);  
17:            bn = (Button)v.findViewById(R.id.b2);  
18:            bn.setOnClickListener(new OnClickListener() {  
19:                 @Override  
20:                 public void onClick(View v) {  
21:                      // TODO Auto-generated method stub  
22:                 FragmentManager fm = getFragmentManager();  
23:                 FragmentTransaction ft = fm.beginTransaction();  
24:                 FragmentTwo f2 = new FragmentTwo();  
25:                 ft.add(R.id.fr1_id, f2);  
26:                 ft.commit();  
27:                 }  
28:            });  
29:            return v;  
30:       }  
31:  }  

FragmentTwo.java
1:  package com.fragment2;  
2:  import android.app.Fragment;  
3:  import android.os.Bundle;  
4:  import android.view.LayoutInflater;  
5:  import android.view.View;  
6:  import android.view.ViewGroup;  
7:  public class FragmentTwo extends Fragment{  
8:       @Override  
9:       public View onCreateView(LayoutInflater inflater, ViewGroup container,  
10:                 Bundle savedInstanceState) {  
11:            View v;  
12:            v = inflater.inflate(R.layout.fragment_two, container,false);  
13:            return v;  
14:            }  
15:  }  

fragment_two.xml
1:  <?xml version="1.0" encoding="utf-8"?>  
2:  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
3:    android:layout_width="match_parent"  
4:    android:layout_height="match_parent" >  
5:    <TextView  
6:      android:id="@+id/textView1"  
7:      android:layout_width="wrap_content"  
8:      android:layout_height="wrap_content"  
9:      android:layout_centerHorizontal="true"  
10:      android:layout_centerVertical="true"  
11:      android:text="Welcome to second fragment"  
12:      android:textAppearance="?android:attr/textAppearanceLarge" />  
13:  </RelativeLayout>  

Fragments programming

Watch Video of this topic

Click Here to watch part 2 of this topic

Comments

Popular posts from this blog

Android MySQL Database Operations

In this post we are going to learn about how to connect to MySQL Database from your Android Application and perform database operations. Here we create an android app that contain some login Activity through which the user can retrieve information from database and a registration Activity through which the user can add information into the database.  First you need to have the following components installed in your development machine.  1. Database : Here we use the MySQL database. 2. Web Server : Here we use the Apache Web Server. 3. Server side Scripting Language :   Here we use PHP for server side scripting. 4. Android Development environment : You must install android sdk and android studio.   I recommend you to download and install WAMPSERVER. The wamp server installer contains the following components. Apache Server Application MySQL Database PHP/phpMyAdmin First we have to create the database and table in MySQL. You can use the phpMyAdmin for mange yo

Android Swipe Views with Tabs

In this post we are going to learn about how to integrate the android tab view with the fragments using ViewPager and ActionBar class. For displaying the tabs on the top of the screen you need to interact with the android action bar, this is because the tab views is connected with the action bar. Ads by Google In this example application we make three tabs called "java", "php" and ".Net" and there are three seperate fragement view for each of these tabs. First you need to add the ViewPager into the activity_main.xml file. <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="match_parent" > </android.support.v4.view.ViewPager> Now create three layout files for the fragments. 1. java_layout.xml <?xml version="1.0" encod

"please correct the errors on this form" adsense error simple solution

Many of the bloggers now facing the problem with their adsense widgets. Whenever try to add the new  adsense link unit using the blogger widgets, it shows the error " please correct the errors on this form " as shown bellow. In blogger you can add the adsense units in two ways. First one is adding the adsense using the blogger widgets(Most of the beginners doing this) and the second method is to obtain the adsense code from the adsense login page and place it into the targeted position on the blog. To improve the revenue from adsense you have to place the appropriate ad unit into the right position. The adsense link units are very important for increasing the adsense revenue. So due to this error many of the bloggers are unable to place the link units.  Here is the solution for the problem. 1. Login into your adsense and blogger account. 2. Now make sure that only two adsense widgets (units) are present on your blog, this is because Google allows onl