Item Long Click handler for ListFragment in Android

July 4, 2012

The objective of this article is to create an Android application which handles the long click event on the listfragment items. If you want to see the screenshot of this application, please jump to the end of this article

1. Create an Android Project namely “ListFragmentItemLongClick”

New Android Project

Figure 1: New Android Project

2. Select Android build target for this application

Select Android Build Target

Figure 2: Select Android Build Target

3. Enter application details

Enter application Details

Figure 3: Enter application Details

4. src/in/wptrafficanalyzer/listfragmentitemlongclick/

package in.wptrafficanalyzer.listfragmentitemlongclick;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Toast;

public class CountryListFragment extends ListFragment{
    String[] countries = new String[] {
        "Sri Lanka",
        "North Korea",
        "South Korea",

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

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(inflater.getContext(), android.R.layout.simple_list_item_1,countries);

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

    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub

        OnItemLongClickListener listener = new OnItemLongClickListener() {
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long id) {
                Toast.makeText( getActivity().getBaseContext()  , "Long Clicked " + countries[position] , Toast.LENGTH_SHORT).show();
                return false;



5. res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" >



6. Application in execution

Item Long Click for List Fragment

Figure 4 : Item Long Click for List Fragment


8. Reference

How to hire me?

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

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

For hiring me, please mail your requirements to

My other blogs

Android Knowledge Quiz

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

Tags: , ,

Leave a Reply

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

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner