Itemclick handler for ListFragment in Android

July 3, 2012
By

The objective of this article is to create a multi-pane android application using fragments. In the first pane, the list of country names will be displayed using ListFragment. On clicking a country, its details will be displayed in the second pane. This is the behaviour if the application is viewed in the landscape orientation.

If the application is viewed in portrait orientation, then on clicking a country, the country list will be replaced with the selected country details. Please jump to the end of this article to see the screen-shots of this application in two orientations.


1. Create an Android Project namely “ListFragmentItemClick”

New Android Project

Figure 1: New Android Project


2. Select Android Build Target

Select build Target

Figure 2: Select build Target


3. Enter Application details

Enter Application Details

Figure 3: Enter Application Details


4. res/values/strings.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello">Hello World, MainActivity!</string>
    <string name="app_name">ListFragmentItemClick</string>
    <color name="blue">#5555ff</color>

</resources>


5. src/in/wptrafficanalyzer/listfragmentitemclick/Country.java


package in.wptrafficanalyzer.listfragmentitemclick;

public class Country {

    /** Array of countries used to display in CountryListFragment */
    static String name[] = new String[] {
        "India",
        "Pakistan",
        "Sri Lanka",
        "China",
        "Bangladesh",
        "Nepal",
        "Afghanistan",
        "North Korea",
        "South Korea",
        "Japan",
        "Bhutan"
    };
}


6. src/in/wptrafficanalyzer/listfragmentitemclick/CountryListFragment.java


package in.wptrafficanalyzer.listfragmentitemclick;

import android.app.Activity;
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;
import android.widget.Toast;

public class CountryListFragment extends ListFragment{

    ListFragmentItemClickListener ifaceItemClickListener;

    /** An interface for defining the callback method */
    public interface ListFragmentItemClickListener {
        /** This method will be invoked when an item in the ListFragment is clicked */
        void onListFragmentItemClick(int position);
    }

    /** A callback function, executed when this fragment is attached to an activity */
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try{
            /** This statement ensures that the hosting activity implements ListFragmentItemClickListener */
            ifaceItemClickListener = (ListFragmentItemClickListener) activity;
        }catch(Exception e){
            Toast.makeText(activity.getBaseContext(), "Exception",Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        /** Data source for the ListFragment */
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(inflater.getContext(), android.R.layout.simple_list_item_1, Country.name);

        /** Setting the data source to the ListFragment */
        setListAdapter(adapter);

        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {

        /** Invokes the implementation of the method onListFragmentItemClick in the hosting activity */
        ifaceItemClickListener.onListFragmentItemClick(position);

    }

}


7. res/layout/main.xml


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

    <fragment
        android:id="@+id/country_list_fragment"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:name="in.wptrafficanalyzer.listfragmentitemclick.CountryListFragment"
    />
</LinearLayout>
  • This is a single pane layout which is used when the application is in portrait orientation

8. res/layout-land/main.xml


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

    <fragment
        android:id="@+id/country_list_fragment"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:name="in.wptrafficanalyzer.listfragmentitemclick.CountryListFragment"
    />

    <FrameLayout
        android:id="@+id/detail_fragment_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_gravity="center"
    >

    </FrameLayout>

</LinearLayout>

  • This is a double pane layout which is used when the application is in landscape orientation

9. src/in/wptrafficanalyzer/listfragmentitemclick/MainActivity.java


package in.wptrafficanalyzer.listfragmentitemclick;

import in.wptrafficanalyzer.listfragmentitemclick.CountryListFragment.ListFragmentItemClickListener;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;

public class MainActivity extends Activity implements ListFragmentItemClickListener {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    /** This method will be executed when the user clicks on an item in the listview */
    @Override
    public void onListFragmentItemClick(int position) {

        /** Getting the orientation ( Landscape or Portrait ) of the screen */
        int orientation = getResources().getConfiguration().orientation;

        /** Landscape Mode */
        if(orientation == Configuration.ORIENTATION_LANDSCAPE ){
            /** Getting the fragment manager for fragment related operations */
            FragmentManager fragmentManager = getFragmentManager();

            /** Getting the fragmenttransaction object, which can be used to add, remove or replace a fragment */
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

            /** Getting the existing detailed fragment object, if it already exists.
            *  The fragment object is retrieved by its tag name
            * */
            Fragment prevFrag = fragmentManager.findFragmentByTag("in.wptrafficanalyzer.country.details");

            /** Remove the existing detailed fragment object if it exists */
            if(prevFrag!=null)
                fragmentTransaction.remove(prevFrag);

            /** Instantiating the fragment CountryDetailsFragment */
            CountryDetailsFragment fragment = new CountryDetailsFragment();

            /** Creating a bundle object to pass the data(the clicked item's position) from the activity to the fragment */
            Bundle b = new Bundle();

            /** Setting the data to the bundle object */
            b.putInt("position", position);

            /** Setting the bundle object to the fragment */
            fragment.setArguments(b);

            /** Adding the fragment to the fragment transaction */
            fragmentTransaction.add(R.id.detail_fragment_container, fragment,"in.wptrafficanalyzer.country.details");

            /** Adding this transaction to backstack */
            fragmentTransaction.addToBackStack(null);

            /** Making this transaction in effect */
            fragmentTransaction.commit();

        }else{
            /** Portrait Mode or Square mode */
            /** Creating an intent object to start the CountryDetailsActivity */
            Intent intent = new Intent("in.wptrafficanalyzer.CountryDetailsActivity");

            /** Setting data ( the clicked item's position ) to this intent */
            intent.putExtra("position", position);

            /** Starting the activity by passing the implicit intent */
            startActivity(intent);
        }
    }
}

  • This is the entry class to the application
  • This class implements the interface ListFragmentItemClickListener to handle the list item click event

10. res/layout/country_details_fragment_layout.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:id="@+id/country_details"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25dp"
        android:layout_gravity="center"
        android:textColor="@color/blue"
    />
</LinearLayout>

  • This is the layout used by CountryDetailsFragment

11. src/in/wptrafficanalyzer/listfragmentitemclick/CountryDetailsFragment.java


package in.wptrafficanalyzer.listfragmentitemclick;

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

public class CountryDetailsFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        /** Inflating the layout country_details_fragment_layout to the view object v */
        View v = inflater.inflate(R.layout.country_details_fragment_layout, null);

        /** Getting the textview object of the layout to set the details */
        TextView tv = (TextView) v.findViewById(R.id.country_details);

        /** Getting the bundle object passed from MainActivity ( in Landscape mode )  or from
        *  CountryDetailsActivity ( in Portrait Mode )
        * */
        Bundle b = getArguments();

        /** Getting the clicked item's position and setting corresponding details in the textview of the detailed fragment */
        tv.setText("Details of " + Country.name[b.getInt("position")]);

        return v;
    }
}

  • This fragment is used to show the details of the country

12. res/layout/country_details_activity_layout.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"
    android:id="@+id/country_details_fragment_container"
>
</LinearLayout>
  • This layout will be used when the application is in portrait orientation

13. src/in/wptrafficanalyzer/listfragmentitemclick/CountryDetailsActivity.java


package in.wptrafficanalyzer.listfragmentitemclick;

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

public class CountryDetailsActivity extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /** Setting the layout for this activity */
        setContentView(R.layout.country_details_activity_layout);

        /** Getting the fragment manager for fragment related operations */
        FragmentManager fragmentManager = getFragmentManager();

        /** Getting the fragmenttransaction object, which can be used to add, remove or replace a fragment */
        FragmentTransaction fragmentTransacton = fragmentManager.beginTransaction();

        /** Instantiating the fragment CountryDetailsFragment */
        CountryDetailsFragment detailsFragment = new CountryDetailsFragment();

        /** Creating a bundle object to pass the data(the clicked item's position) from the activity to the fragment */
        Bundle b = new Bundle();

        /** Setting the data to the bundle object from the Intent*/
        b.putInt("position", getIntent().getIntExtra("position", 0));

        /** Setting the bundle object to the fragment */
        detailsFragment.setArguments(b);

        /** Adding the fragment to the fragment transaction */
        fragmentTransacton.add(R.id.country_details_fragment_container, detailsFragment);

        /** Making this transaction in effect */
        fragmentTransacton.commit();

    }
}

  • This activity is loaded when a country is clicked in the portrait orientation

14. AndroidManfest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.wptrafficanalyzer.listfragmentitemclick"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="14" />

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

        <activity
            android:name=".CountryDetailsActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="in.wptrafficanalyzer.CountryDetailsActivity" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
</application>
</manifest>

  • When the application is in portrait orientation, the CountryDetailsFragment is loaded into CountryDetailsActivity

15. The screen shot of the application in landscape orientation

Application in Landscape Orientation

Figure 4: Application in Landscape Orientation. Both fragments are listed in one activity



16. The screen shot of the application in portrait orientation

ListFragment in the MainActivity

Figure 5 : ListFragment in the MainActivity

Details Activity with Details Fragment

Figure 6: Details Activity with Details Fragment.



17. Download


18. Reference

http://developer.android.com/guide/index.html


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , , , ,

7 Responses to Itemclick handler for ListFragment in Android

  1. Techi on December 15, 2012 at 11:31 am

    Thanks for such wonderful examples, I have been learning a lot from your tuts. But in this example I tend to have some issues:
    1) where is TAG=”in.wptrafficanalyzer.country.details” defined.
    2) The download code is not being accepted by eclipse, any idea why.

  2. Dnyaneshwar on March 14, 2013 at 5:43 pm

    Hi…
    Sir u displayed one item that is details of japan…….but…i my project i want to display a list of details then what i want to do…….ex
    1)India is my country
    2)I am indian
    3)i love india
    then what i want to do please give one example …….i m new in android……..now i m doing project for college submission…..reply fast sir i am waiting..

  3. Patel Bhavesh on March 17, 2013 at 11:39 am

    sir,I developed the custom listviewin sherlock fragment.I wanna put click event on this listview item and show the another custom listview on another sherlock fragment????

    what to do ?? tell me??

  4. Lait on June 19, 2013 at 3:24 pm

    Such a nice tutorial…It really helped me a lot :)

  5. KhongChoDoi on July 26, 2015 at 9:43 pm

    thanks, but have error when transaction from portrait screen to orientation screen. You can fix it, thank you.

  6. vikash kumar on February 12, 2016 at 11:40 pm

    I want to create another listview in listfragment and perform some task on click of these items ..like go to other activity .Please help me .

  7. Shilpa on February 24, 2016 at 10:20 am

    Nice tutorial..It worked fro me.

Leave a Reply to KhongChoDoi Cancel reply

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

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner