Android Fragments with Examples

  Total Views : 87
  Comments : 0
  Keywords : Android fragment is a part of an activity and it is called as a sub-activity, Android fragment is a component which is used to implement the functionality that is easily reused in activities

Here we will learn fragments in android with examples and how to use android fragments, android fragments life cycle, list of methods in android fragment lifecycle with examples.

Android Fragments

In android, Fragments are the modular section of an activity design and these are used to represent the behaviour of user interface (UI) in an activity. By using fragments we can create a flexible UI designs that can be adjusted based on the device screen size such as tablets, smartphones.

 

We can build multi-pane UI by combining multiple fragments in a single activity and we can reuse same fragment in multiple activities. The fragment has its own lifecycle call-backs and accept its own input events.

 

We can add or remove fragments in an activity while activity is running. In android, the fragment will act as a sub-activity and we can reuse it in multiple activities.

 

Generally, in android the fragment must be included in an activity due to that the fragment lifecycle will always effected by the host activity life cycle. In case if we pause an activity, all the fragments related to an activity will also be stopped.

 

In android, we can insert fragment into activity layout by using <fragment> element and by dividing the layout of an activity into fragments, we can modify the appearance of an app design at runtime. We can also implement a fragment without having any user interface (UI).

 

It’s an optional to use fragments into activity but by doing this it will improve the flexibility of our app UI and make it easier to adjust our app design based on the device size.

 

Following is the example of defining a multiple fragments in single activity for the tablet design to display the details of an item which we selected in app, but separated for mobile design.

 

Android Fragments -  Fragments in Single Activity for table and mobile devices

 

If you observe above example for Tablet we defined an Activity A with two fragments such as one is to show the list of items and second one is to show the details of item which we selected in first fragment.

 

For Handset device, there is no enough space to show both the fragments in single activity, so the Activity A includes first fragment to show the list of items and the Activity B which includes another fragment to display the details of an item which is selected in Activity A.

 

For example, GMAIL app is designed with multiple fragments, so the design of GMAIL app will be varied based on the size of device such as tablet or mobile device.

 

Table View

 

Android Fragments - Gmail App with Fragments in Table View

 

Mobile View

 

Android Fragments - Gmail App with Fragments in Mobile View

Android Fragment Life Cycle

Following is pictorial representation of android fragment life cycle while its activity is running.

 

Android Fragments - Lifecycle of android fragments process flow

 

Following are the list of methods which will perform during the lifecycle of fragment in android applications.

 

MethodDescription
onAttach() It is called when the fragment has been associated with an activity.
onCreate() It is used to initialize the fragment.
onCreteView() It is used to create a view hierarchy associated with the fragment.
onActivityCreated() It is called when the fragment activity has been created and the fragment view hierarchy instantiated.
onStart() It is used to make the fragment visible.
onResume() It is used to make the fragment visible in an activity.
onPause() It is called when fragment is no longer visible and it indicates that the user is leaving the fragment.
onStop() It is called to stop the fragment using onStop() method.
onDestoryView() The view hierarcy which associated with the fragment is being removed after executing this method.
onDestroy() It is called to perform a final clean up of the fragments state.
onDetach() It is called immediately after the fragment disassociated from the activity.

Android Fragments Examples

Following is the example of creating a two fragments, two buttons and showing the respective fragment when click on button in android application.

Create a new android application using android studio and give names as Fragments. In case if you are not aware of creating an app in android studio check this article Android Hello World App.

 

Now we need to create our own custom fragment layout files (listitems_info.xml, details_info.xml) in \res\layout path to display those fragments in main layout for that right click on your layout folder à Go to New à select Layout resource file and give name as listitems_info.xml.

 

Once we create a new file listitems_info.xml, open it and write the code like as shown below

Listitems_info.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
android:orientation="vertical" android:layout_width="match_parent"
   
android:layout_height="match_parent">
    <
ListView
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:id="@android:id/list" />
</
LinearLayout>

Same way create another file details_info.xml, open it and write the code like as shown below

details_info.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
android:orientation="vertical" android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
android:background="#0079D6">
    <
TextView
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:textColor="#ffffff"
       
android:layout_marginTop="200px"
       
android:layout_marginLeft="200px"
       
android:id="@+id/Name"/>
    <
TextView
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_marginLeft="200px"
       
android:textColor="#ffffff"
       
android:id="@+id/Location"/>
</
LinearLayout>

 

Now we need to create our own custom fragment class files (ListMenuFragment.java, DetailsFragment.java) in \java\com.tutlane.fragmentsexample path to bind and display data in fragments for that right click on your application folder à Go to New à select Java Class and give name as DetailsFragment.java.

 

Once we create a new file DetailsFragment.java, open it and write the code like as shown below

DetailsFragment.java

package com.tutlane.fragmentsexample;

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

/**
 * Created by tutlane on 06-08-2017.
 */

public class DetailsFragment extends Fragment {
    TextView
name,location;
   
@Override
   
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.
details_info, container, false);
       
name = (TextView)view.findViewById(R.id.Name);
       
location = (TextView)view.findViewById(R.id.Location);
       
return view;
    }
   
public void change(String uname, String ulocation){
       
name.setText(uname);
       
location.setText(ulocation);
    }
}

If you observe above code we extended class with Fragment and used LayoutInflater to show the details of fragment. We defined a function change() to change the text in textview.

 

Same way create another file ListMenuFragment.java, open it and write the code like as shown below

ListMenuFragment.java

package com.tutlane.fragmentsexample;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

/**
 * Created by tutlane on 06-08-2017.
 */
public class ListMenuFragment extends ListFragment {
    String[]
users = new String[] { "Suresh","Rohini","Trishika","Praveen","Sateesh","Madhav" };
    String[]
location = new String[]{"Hyderabad","Guntur","Hyderabad","Bangalore","Vizag","Nagpur"};
   
@Override
   
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view =inflater.inflate(R.layout.
listitems_info, container, false);
        ArrayAdapter<String> adapter =
new ArrayAdapter<String>(getActivity(),
                android.R.layout.
simple_list_item_1, users);
        setListAdapter(adapter);
       
return view;
    }
   
@Override
   
public void onListItemClick(ListView l, View v, int position, long id) {
        DetailsFragment txt = (DetailsFragment)getFragmentManager().findFragmentById(R.id.
fragment2);
        txt.change(
"Name: "+ users[position],"Location : "+ location[position]);
        getListView().setSelector(android.R.color.
holo_blue_dark);
    }
}

If you observe above code we extended our class using ListFragment and we defined two array of strings users, location which contains names and locations. We defined onListItemClick event to update the name and location in DetailsFragment based on the list item which we clicked.

 

Now we need to display our fragments horizontally side by side in main layout for that open activity_main.xml file and write code like as shown below

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
xmlns:tools="http://schemas.android.com/tools"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
android:orientation="horizontal"
   
tools:context="com.tutlane.fragmentsexample.MainActivity">

    <
fragment
       
android:layout_height="match_parent"
       
android:layout_width="350px"
       
class="com.tutlane.fragmentsexample.ListMenuFragment"
       
android:id="@+id/fragment"/>
    <
fragment
       
android:layout_width="match_parent"
       
android:layout_height="match_parent"
       
class="com.tutlane.fragmentsexample.DetailsFragment"
       
android:id="@+id/fragment2"/>
</
LinearLayout>

We are not going to make any modifications for our main activity file (MainActivity.java) and manifest file (AndroidMainfest.xml).

Output of Android Fragments Example

When we run above example in android emulator we will get a result like as shown below

 

Android Fragments Example Result or Output

 

This is how we can use fragments in activity to build multi-pane UI to adjust android application layout based on size of device such as tablets or smart phones, etc. based on our requirements. 

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User