Home » Android » Types of Fragment

Types of Fragment

Welcome to the Third and last module of this series. In this module we will learn about types of Fragment like list fragment, map fragment and Dialog fragment.

Below are the topics that we will cover in this module:

  • What is List Fragment?
  • Example to create simple List Fragment.
  • Example to create custom List Fragment.
  • What is Map Fragment?
  • Prerequisite for map Fragments
  • Example to create map Fragment
  • Dialog Fragment

 

What is List Fragment?
List Fragment is the fragment that display list of items by binding it to a data source like an array. Let’s create an example for list fragment.

Example to create simple List Fragment
SimpleListFragment.java

import android.app.ListFragment;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class SimpleListFragment extends ListFragment{

   String[] speakerList = new String[]{
    "Himanshu Chahar",
    "Piyush Chahar",
    "John Bosco",
    "Kim Williams"
   };

@Override
public void onActivityCreated(Bundle savedInstanceState) {
   // TODO Auto-generated method stub
   super.onActivityCreated(savedInstanceState);
   ArrayAdapter<String> courseTitlesAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,android.R.id.text1,speakerList);
   setListAdapter(courseTitlesAdapter);
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
   // TODO Auto-generated method stub
   super.onListItemClick(l, v, position, id);
   Toast.makeText(getActivity(), "clicked: "+speakerList[position],Toast.LENGTH_SHORT).show();
  }
}

Above class shows how to create simple list fragment from an string array, clicking on an item will display the speaker name in toast. There is not much to explain, the code is pretty much straight forward.

simple_list_fragment

Simple List Fragment

 

Example to create custom List Fragment
In this example we will create a list which will have an image and speaker name.

Create an xml which will have <ListView/> widget

custom_list_fragment.xml

<?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:orientation="vertical" >

<ListView android:id="@id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

</LinearLayout>

Create a class which will have data that we want to display in the list.

CustomListFragment.java

import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.codeureka.fragmentsexample.CustomListAdapter;
import com.codeureka.fragmentsexample.R;

public class CustomListFragment extends ListFragment{

   String[] speakerList = new String[]{
    "Himanshu Chahar",
    "Piyush Chahar",
    "John Bosco",
    "Kim Williams"
   };

   ListView listView = null;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
   // TODO Auto-generated method stub
   View view = inflater.inflate(R.layout.custom_list_fragment, container,false);
   listView = (ListView)view.findViewById(android.R.id.list);
   return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
   // TODO Auto-generated method stub
   super.onActivityCreated(savedInstanceState);
   CustomListAdapter adapter = new CustomListAdapter(getActivity(), speakerList);
   setListAdapter(adapter);
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
   // TODO Auto-generated method stub
   super.onListItemClick(l, v, position, id);
   Toast.makeText(getActivity(), "clicked: "+speakerList[position],Toast.LENGTH_SHORT).show();
  }
}

In above code we are inflating the view by using inflate() method. To create a custom list I have defined custom class called customListAdapter, and I am passing context and speakerArray to its constructor.

Now create another xml file which will be the layout of each list item.

custom_list_row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="12dp">

<ImageView
android:id="@+id/imageViewCustomList"
android:layout_width="wrap_content"
android:layout_height="wrap_content" 
android:src="@drawable/user"
android:layout_alignParentLeft="true"
android:layout_weight="1"/>

<TextView
android:id="@+id/textViewCustomList"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_alignParentRight="true"
android:text="TextView" />

</RelativeLayout>

Above xml has one <ImageView/> to display the image and one <TextView/> to display the speaker’s name.
Now final step is to create the customListAdapter class which we used in CustomListFragment.java class. This class will extend BaseAdapter abstract class and implement its methods.

CustomListAdapter.java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomListAdapter extends BaseAdapter{

   String[] mSpeakerList = null;
   private LayoutInflater inflater;

public CustomListAdapter(Context context, String[] speakerData) {
   inflater = LayoutInflater.from(context);
   mSpeakerList = speakerData; 
}

private class ViewHolder {
   ImageView imageView;
   TextView speakerName;
}

@Override
public int getCount() {
   // TODO Auto-generated method stub
   return mSpeakerList.length;
}

@Override
public Object getItem(int position) {
   // TODO Auto-generated method stub
   return position;
}

@Override
public long getItemId(int position) {
   // TODO Auto-generated method stub
   return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
   // TODO Auto-generated method stub
   ViewHolder viewHolder = null;
   if(convertView ==null){
      convertView = inflater.inflate(R.layout.custom_list_row, null);
      viewHolder = new ViewHolder();
      viewHolder.speakerName = (TextView) convertView.findViewById(R.id.textViewCustomList);
      viewHolder.imageView = (ImageView) convertView.findViewById(R.id.imageViewCustomList);
     convertView.setTag(viewHolder);
   }else{
      viewHolder = (ViewHolder)convertView.getTag();
   }

   viewHolder.speakerName.setText(mSpeakerList[position]);
   return convertView;
  }
}

If you have worked on custom list view before then you must be familiar with this class. I have created a private Viewholder class for custom view. In getView() I am checking if convertView is null, then create the instance of ViewHolder class or else use the same instance. And finally I am passing each item from speakerArray to the ViewHolder’s textView.

custom_list_fragment

Custom List Fragment

 

What is Map Fragment?

MapFragment is another type of fragment which can be used to display Google Maps in your application.

 

Prerequisite for map Fragments

Before moving further there are few steps that you need to follow to get the Google Maps API key which will be required to add maps in your application.

1. Go to the Google APIs Console
2. Click on APIs & Auth
3. In APIs section enable ‘Google Maps Android API v2’
4. In the left navigation bar, click Credentials.
5. Click on “Create New key” and select Android key.
6. In the Dialog box: enter your SHA-1 fingerprint,then a semicolon,then your application’s package name.
i.e. (your SHA-1 fingerprint)(semicolon)(your application’s package name)
7. Click generate and you will get your new API key

After getting the API key, the next step it to add map fragment in your application.

 

Example to create map Fragment

Basically there are 4 main steps that you need to follow to add Google maps in your application
1. Modify your AndroidManifest.xml

====Add following permissions:

<permission
android:name=”com.codeureka.mapfragment.permission.MAPS_RECEIVE”
android:protectionLevel=”signature” />

<uses-permission android:name=”com.codeureka.mapfragment.permission.MAPS_RECEIVE” />
<uses-permission android:name=”android.permission.INTERNET” />
<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE” />
<uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION” />
<uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION” />
<uses-permission android:name=”com.google.android.providers.gsf.permission.READ_GSERVICES” />

====Add <uses-feature> tag because Google maps use openGl

<uses-feature
android:glEsVersion=”0×00020000″
android:required=”true” />

===Add meta-data tag before closing application tag <application/>:

<meta-data
android:name=”com.google.android.maps.v2.API_KEY”
android:value=”YOUR_API_KEY” />

2. Import GooglePlay service to your workspace and add that as a library in your project

Import GooglePlay service to your workspace
File -> Import-> Android -> Existing Android Code into Workspace
Browse to your_android_sdk_folder_path\extras\google\google_play_services\libproject\google-play-services_lib

add GooglePlay service as a library in your project
Right click on your project -> properties -> android -> under library section click add -> select googleplay service -> apply

3. Add fragment to layout xml file

Use “com.google.android.gms.maps.SupportMapFragment” as android:name

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />

</RelativeLayout>

4. Create class which extends FragmentActivity

MapFragmentActivity.java

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapFragmentActivity extends FragmentActivity {
   GoogleMap map;

@Override
protected void onCreate(Bundle arg0) {
   // TODO Auto-generated method stub
   super.onCreate(arg0);
   setContentView(R.layout.map_fragment_activity);

   GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()); // check whether the Google play service is available or not 
   map = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); // get the reference of Google maps
   map.setMyLocationEnabled(true); // enables mylocation layer on map and display user's current location

   map.addMarker(new MarkerOptions() // addMarker() method adds the marker on map, MarkerOptions create new set of marker options
      .position(new LatLng(17.451121,78.381902)) // latitude,longitude position of marker
      .title("Work Place") // title displayed when clicked on marker
      .snippet("India") // marker text
      .icon(BitmapDescriptorFactory.fromResource(R.drawable.current_location))); // custom icon do be displayed at given lat,long position
  }
}

That’s it, if you run the code you will see the Google maps on your screen.
I have added comments in MapFragmentActivity.java so you can understand each line of code.

map_fragment

Map Fragment

 

Dialog Fragment

Dialog fragment is another type of fragment which is used to display dialog box. Below is the code to display custom dialog box.

simple_dialog_fragment.xml

<?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:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="0px"
android:layout_weight="1"
android:gravity="center_horizontal"
android:text="Would you like to rate this app?"
android:textAppearance="?android:attr/textAppearanceMedium" />

<RatingBar
android:id="@+id/dialogFragRating"
style="@style/customRatingBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numStars="5"
android:rating="3" />

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0px"
android:layout_weight="3"
android:orientation="horizontal" >

<Button
android:id="@+id/dialogFragRate"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Rate" />

<Button
android:id="@+id/dialogFragLater"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Later" />

<Button
android:id="@+id/dialogFragNever"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Never" />
</LinearLayout>

</LinearLayout>

 

SimpleDialogFragment.java

import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.Toast;

public class SimpleDialogFragment extends DialogFragment implements View.OnClickListener{
   RatingBar ratingBar;
   Button btnRate, btnLater, btnNever;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
   // TODO Auto-generated method stub
   View view = inflater.inflate(R.layout.simple_dialog_fragment, container,false);

   ratingBar = (RatingBar)view.findViewById(R.id.dialogFragRating);
   btnRate = (Button)view.findViewById(R.id.dialogFragRate);
   btnLater = (Button)view.findViewById(R.id.dialogFragLater);
   btnNever = (Button)view.findViewById(R.id.dialogFragNever);

   btnRate.setOnClickListener(this);
   btnLater.setOnClickListener(this);
   btnNever.setOnClickListener(this);

   Dialog dialog = getDialog();
   if(dialog!=null){
      dialog.setTitle("Rate App");
   }
   return view;
}
@Override
public void onClick(View v) {
   // TODO Auto-generated method stub
   switch (v.getId()) {
      case R.id.dialogFragRate:
        Toast.makeText(getActivity(), "RATE", Toast.LENGTH_SHORT).show();
      break;
      case R.id.dialogFragLater:
        Toast.makeText(getActivity(), "LATER", Toast.LENGTH_SHORT).show();
      break;
      case R.id.dialogFragNever:
        Toast.makeText(getActivity(), "NEVER", Toast.LENGTH_SHORT).show();
      break;
      default:
      break;
   }
   dismiss(); 
  }
}

Above code will display RatingBar and three buttons. Creating a Dialog Fragment is same as creating activity class; the only difference is we have to extend the class from DialogFragment.
To show the dialog, create an instance of this class and call show().

SimpleDialogFragment dialogFragment = new SimpleDialogFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
dialogFragment.show(ft, "ShowDialog");

 dialog_fragment

Dialog Fragment

So finally we have come to an end of this series, we have tried to cover almost all the major concepts of android Fragment. Please comment and let us know if you have any suggestion or if you want us to include more topics.

Thanks!!! Happy CoDing…

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>