Implementing ListView Into ActionBarSherlock Fragment Tabs Tutorial

In this tutorial, you will learn how to implement listviews into your ActionBarSherlock fragment tabs. Fragment tabs allow the user to navigate between fragments by selecting the appropriate tab indicator available at the top of the display. We will be creating listviews in the fragment tabs using ActionBarSherlock Library and on listview item click will show results on a new activity. So lets begin…

Start this tutorial by importing your ActionBarSherlock Library into your Eclipse. Add the ActionBarSherlock Library into your project.

Create a new project in Eclipse File > New > Android Application Project. Fill in the details and name your project ABSListViewFragmentTabs.

Application Name : ABSListViewFragmentTabs

Project Name : ABSListViewFragmentTabs

Package Name : com.androidbegin.abslistviewfragmenttabs

Open your MainActivity.java and paste the following codes.

MainActivity.java

package com.androidbegin.abslistviewfragmenttabs;

import com.actionbarsherlock.app.SherlockFragmentActivity;

import android.support.v4.app.FragmentTabHost;
import android.os.Bundle;

public class MainActivity extends SherlockFragmentActivity {
	// Declare Variables	
	private FragmentTabHost mTabHost;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Set the view from main_fragment.xml
		setContentView(R.layout.main_fragment);

		// Locate android.R.id.tabhost in main_fragment.xml
		mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);

		// Create the tabs in main_fragment.xml
		mTabHost.setup(this, getSupportFragmentManager(), R.id.tabcontent);

		// Create Tab1 with a custom image in res folder
		mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("", getResources().getDrawable(R.drawable.tab1)),
				FragmentTab1.class, null);

		// Create Tab2
		mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Tab2"),
				FragmentTab2.class, null);

		}
}

We have created 2 tabs with FragmentTabHost, and by selecting the appropriate tab will show different listviews.

Next, create a graphical layout for the MainActivity that shows the FragmentTabHost. Go to res > layout > Right Click on layout > New >Android XML File

Name your new XML file main_fragment.xml and paste the following codes.

main_fragment.xml

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

    <android.support.v4.app.FragmentTabHost
        android:id="@android:id/tabhost"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <FrameLayout
            android:id="@+id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </android.support.v4.app.FragmentTabHost>

</LinearLayout>

Next, create a class for FragmentTab1. Go to File > New > Class and name it FragmentTab1.java. Select your package named com.androidbegin.abslistviewfragmenttabs and click Finish.

Open your FragmentTab1.java and paste the following codes.

FragmentTab1.java

package com.androidbegin.abslistviewfragmenttabs;

import com.actionbarsherlock.app.SherlockFragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class FragmentTab1 extends SherlockFragment {
	String[] rank;
	String[] country;
	String[] population;
	int[] flag;
	ListView list;
	ListViewAdapter adapter;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragmenttab1, container,
				false);
		// Generate sample data
		rank = new String[] { "1", "2", "3", "4", "5" };

		country = new String[] { "China", "India", "United States",
				"Indonesia", "Brazil" };

		population = new String[] { "1,354,040,000", "1,210,193,422",
				"315,761,000", "237,641,326", "193,946,886" };

		flag = new int[] { R.drawable.china, R.drawable.india,
				R.drawable.unitedstates, R.drawable.indonesia,
				R.drawable.brazil };

		// Locate the ListView in fragmenttab1.xml
		list = (ListView) rootView.findViewById(R.id.listview);

		// Pass results to ListViewAdapter Class
		adapter = new ListViewAdapter(getActivity(), rank, country, population,
				flag);
		// Binds the Adapter to the ListView
		list.setAdapter(adapter);
		// Capture clicks on ListView items
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// Send single item click data to SingleItemView Class
				Intent i = new Intent(getActivity(), SingleItemView.class);
				// Pass all data rank
				i.putExtra("rank", rank);
				// Pass all data country
				i.putExtra("country", country);
				// Pass all data population
				i.putExtra("population", population);
				// Pass all data flag
				i.putExtra("flag", flag);
				// Pass a single position
				i.putExtra("position", position);
				// Open SingleItemView.java Activity
				startActivity(i);
			}

		});
		return rootView;
	}

}

In FragmentTab1, we have created a listview and some sample data’s into a string and integer array. The data’s are then passed into  a ListViewAdapter class to show it on the listview. An on listview item click will pass the selected data and position to a new activity.

Next, create a graphical layout for FragmentTab1 that shows the listview. Go to res > layout > Right Click on layout > New >Android XML File

Name your new XML file fragmenttab1.xml and paste the following codes.

fragmenttab1.xml

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

    <ListView
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</RelativeLayout>

Next, create a class for FragmentTab2. Go to File > New > Class and name it FragmentTab1.java. Select your package named com.androidbegin.abslistviewfragmenttabs and click Finish.

Open your FragmentTab2.java and paste the following codes.

FragmentTab2.java

package com.androidbegin.abslistviewfragmenttabs;

import com.actionbarsherlock.app.SherlockFragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class FragmentTab2 extends SherlockFragment {
	String[] rank;
	String[] country;
	String[] population;
	int[] flag;
	ListView list;
	ListViewAdapter adapter;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragmenttab2, container,
				false);
		// Generate sample data
		rank = new String[] { "6", "7", "8", "9", "10" };

		country = new String[] { "Pakistan", "Nigeria", "Bangladesh", "Russia",
				"Japan" };

		population = new String[] { "182,912,000", "170,901,000",
				"152,518,015", "143,369,806", "127,360,000" };

		flag = new int[] { R.drawable.pakistan, R.drawable.nigeria,
				R.drawable.bangladesh, R.drawable.russia, R.drawable.japan };

		// Locate the ListView in fragmenttab2.xml
		list = (ListView) rootView.findViewById(R.id.listview);

		// Pass results to ListViewAdapter Class
		adapter = new ListViewAdapter(getActivity(), rank, country, population,
				flag);
		// Binds the Adapter to the ListView
		list.setAdapter(adapter);
		// Capture clicks on ListView items
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// Send single item click data to SingleItemView Class
				Intent i = new Intent(getActivity(), SingleItemView.class);
				// Pass all data rank
				i.putExtra("rank", rank);
				// Pass all data country
				i.putExtra("country", country);
				// Pass all data population
				i.putExtra("population", population);
				// Pass all data flag
				i.putExtra("flag", flag);
				// Pass a single position
				i.putExtra("position", position);
				// Open SingleItemView.java Activity
				startActivity(i);
			}

		});
		return rootView;
	}

}

In FragmentTab2, we have created a listview and some sample data’s into a string and integer array. The data’s are then passed into  a ListViewAdapter class to show it on the listview. An on listview item click will pass the selected data and position to a new activity.

Next, create a graphical layout for FragmentTab2 that shows the listview. Go to res > layout > Right Click on layout > New >Android XML File

Name your new XML file fragmenttab2.xml and paste the following codes.

fragmenttab2.xml

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

    <ListView
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</RelativeLayout>

Next, create a class for ListViewAdapter. Go to File > New > Class and name it ListViewAdapter.java. Select your package named com.androidbegin.abslistviewfragmenttabs and click Finish.

Open your ListViewAdapter.java and paste the following codes.

ListViewAdapter.java

package com.androidbegin.abslistviewfragmenttabs;

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 ListViewAdapter extends BaseAdapter {

	// Declare Variables
	Context context;
	String[] rank;
	String[] country;
	String[] population;
	int[] flag;
	LayoutInflater inflater;

	public ListViewAdapter(Context context, String[] rank, String[] country,
			String[] population, int[] flag) {
		this.context = context;
		this.rank = rank;
		this.country = country;
		this.population = population;
		this.flag = flag;
	}

	public int getCount() {
		return rank.length;
	}

	public Object getItem(int position) {
		return null;
	}

	public long getItemId(int position) {
		return 0;
	}

	public View getView(int position, View convertView, ViewGroup parent) {

		// Declare Variables
		TextView txtrank;
		TextView txtcountry;
		TextView txtpopulation;
		ImageView imgflag;

		inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View itemView = inflater.inflate(R.layout.listview_item, parent, false);

		// Locate the TextViews in listview_item.xml
		txtrank = (TextView) itemView.findViewById(R.id.rank);
		txtcountry = (TextView) itemView.findViewById(R.id.country);
		txtpopulation = (TextView) itemView.findViewById(R.id.population);
		// Locate the ImageView in listview_item.xml
		imgflag = (ImageView) itemView.findViewById(R.id.flag);

		// Capture position and set to the TextViews
		txtrank.setText(rank[position]);
		txtcountry.setText(country[position]);
		txtpopulation.setText(population[position]);

		// Capture position and set to the ImageView
		imgflag.setImageResource(flag[position]);

		return itemView;
	}
}

In this ListViewAdapter, texts and images are populated into the listview followed by the positions.

We have prepared some sample images for this tutorial. Put your downloaded sample images into your res > drawable-hdpi.

Sample Images

[wpfilebase tag=file id=35 tpl=download-button /]

Next, create a graphical layout for ListView Items. Go to res > layout > Right Click on layout > New >Android XML File

Name your new XML file listview_item.xml and paste the following codes.

listview_item.xml

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

    <TextView
        android:id="@+id/ranklabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/ranklabel" />

    <TextView
        android:id="@+id/rank"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/ranklabel" />

    <TextView
        android:id="@+id/countrylabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/ranklabel"
        android:text="@string/countrylabel" />

    <TextView
        android:id="@+id/country"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/rank"
        android:layout_toRightOf="@+id/countrylabel" />

    <TextView
        android:id="@+id/populationlabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/countrylabel"
        android:text="@string/populationlabel" />

    <TextView
        android:id="@+id/population"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/country"
        android:layout_toRightOf="@+id/populationlabel" />

    <ImageView
        android:id="@+id/flag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:background="#000000"
        android:padding="1dp" />

</RelativeLayout>

Next, create a class for SingleItemView. Go to File > New > Class and name it SingleItemView.java. Select your package named com.androidbegin.abslistviewfragmenttabs and click Finish.

Open your SingleItemView.java and paste the following codes.

SingleItemView.java

package com.androidbegin.abslistviewfragmenttabs;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

public class SingleItemView extends Activity {
    // Declare Variables
    TextView txtrank;
    TextView txtcountry;
    TextView txtpopulation;
    ImageView imgflag;
    String[] rank;
    String[] country;
    String[] population;
    int[] flag;
    int position;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.singleitemview);
        // Retrieve data from MainActivity on item click event
        Intent i = getIntent();
        // Get a single position
        position = i.getExtras().getInt("position");
        // Get the list of rank
        rank = i.getStringArrayExtra("rank");
        // Get the list of country
        country = i.getStringArrayExtra("country");
        // Get the list of population
        population = i.getStringArrayExtra("population");
        // Get the list of flag
        flag = i.getIntArrayExtra("flag");

        // Locate the TextViews in singleitemview.xml
        txtrank = (TextView) findViewById(R.id.rank);
        txtcountry = (TextView) findViewById(R.id.country);
        txtpopulation = (TextView) findViewById(R.id.population);

        // Locate the ImageView in singleitemview.xml
        imgflag = (ImageView) findViewById(R.id.flag);

        // Load the text into the TextViews followed by the position
        txtrank.setText(rank[position]);
        txtcountry.setText(country[position]);
        txtpopulation.setText(population[position]);

        // Load the image into the ImageView followed by the position
        imgflag.setImageResource(flag[position]);
    }
}

On listview item click, data’s are passed from the fragments into the SingleItemView.java class. Then the results are set into the textviews and imageviews.

Next, create a graphical layout for SingleItemView. Go to res > layout > Right Click on layout > New >Android XML File

Name your new XML file singleitemview.xml and paste the following codes.

singleitemview.xml

<?xml version="1.0" encoding="utf-8"?>
<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" >

    <TextView
        android:id="@+id/ranklabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/ranklabel" />

    <TextView
        android:id="@+id/rank"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/ranklabel" />

    <TextView
        android:id="@+id/countrylabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/ranklabel"
        android:text="@string/countrylabel" />

    <TextView
        android:id="@+id/country"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/rank"
        android:layout_toRightOf="@+id/countrylabel" />

    <TextView
        android:id="@+id/populationlabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/countrylabel"
        android:text="@string/populationlabel" />

    <TextView
        android:id="@+id/population"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/country"
        android:layout_toRightOf="@+id/populationlabel" />

    <ImageView
        android:id="@+id/flag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:background="#000000"
        android:padding="1dp" />

</RelativeLayout>

Next, change the application name and texts. Open your strings.xml in your res > values folder and paste the following codes.
strings.xml

<resources>

    <string name="app_name">ABS ListView Fragment Tabs Tutorial</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="ranklabel">"Rank : "</string>
    <string name="countrylabel">"Country : "</string>
    <string name="populationlabel">"Population : "</string>

</resources>

In your AndroidManifest.xml, we need to declare an activity for SingleItemView.java. Open your AndroidManifest.xml and paste the following codes.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidbegin.abslistviewfragmenttabs"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="1"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/Theme.Sherlock" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SingleItemView" >
        </activity>
    </application>

</manifest>

Output:

ABS ListView Fragment Tabs ScreenShots

Source Code  

[purchase_link id=”7987″ text=”Purchase to Download Source Code” style=”button” color=”green”]

Latest comments

Thanks a lot for this tutorial

Henri Gustave

Implementing ListView Into ActionBarSherlock Fragment Tabs Tutorial

Hi....I also have the same problem. How did you solve it?

bdh

Implementing ListView Into ActionBarSherlock Fragment Tabs Tutorial

I want to when users button click after here come

ssalt

Implementing ListView Into ActionBarSherlock Fragment Tabs Tutorial

Hi the content of the layout overlap with the tab I asked in stackoverflow http://stackoverflow.com/questions/25108743/layout-overlap-actionbarsherlock-tab

Ali Mahmoud Habib

Implementing ListView Into ActionBarSherlock Fragment Tabs Tutorial