Adding Long Click functionality in List View – Context Menus

This entry is part 35 of 50 in the series Android Development Primer

As we saw in the last post, we can easily handle clicks on the list items. However, often times in our applications we would like to have separate genres of options on the click of the the list items if possible. This is where long clicks come into play. Android provides facilities to handle both regular and long clicks by identifying them separately.

Here, I will show you how to use this facility of Android and separately handle clicks. I am creating a menu here on detecting long clicks. You can do a lot more things as and what you feel like. So start off an activity and follow along. Complete Source Code is at the bottom.

  • Create the layout of the activity and insert a ListView into it.
  • Switch over to the java file and declare the List View. Create the string array to populate the list.
  • Declare and assign the ArrayAdapter to the ListView.
  • Just after this assignment we need to register our ListView for Context Menu. Write the below line:
    registerForContextMenu(lv);
    
  • Close the onCreate() method and create a new method:
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo){
        	menu.add(0, v.getId(), 0, "Edit");
    	    menu.add(0, v.getId(), 0, "Delete");
    }
    
  • Here we are going to provide the user with a couple of options of Edit and Delete the entry. Of course, we are not going to perform these actions here. This is just for demonstration purposes.
  • Save your work and execute it on an emulator or device.

LongClick

Understanding the Code:

  • The menu.add() method we are using here has a constructor add(int groupId, int itemId, int order, CharSequence title).
  • We are providing a value of 0 for both groupId and order. We however are giving each item an itemId which we derive easily from the view argument to the method.

COMPLETE SOURCE CODE

activity_main.xml

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <ListView
        android:id="@+id/android:list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >
    </ListView>
</RelativeLayout>

MainActivity.java

package com.nero.myfirstapp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Main extends ListActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String values[]=new String[]{"Vergil", "Dante", "Sparda", "Nero", "Arkham", "Agni", "Rudra", "Beowulf", "Nevan"};
        ListView lv = getListView();
        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1,values);
        lv.setAdapter(adapter);
        registerForContextMenu(lv);

        lv.setOnItemClickListener(new OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View view, int position, long id){
        		String item = ((TextView)view).getText().toString();
        		Toast.makeText(getApplicationContext(), "Clicked: "+item, Toast.LENGTH_LONG).show();
        	}
          });
    }
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo){
   	    menu.add(0, v.getId(), 0, "Edit");
	    menu.add(0, v.getId(), 0, "Delete");
	}
}
Series Navigation<< Adding Click functionality in List View – onItemClickListener()Adding Long Click functionality in List View – Context Menus Clicks >>

Leave a Reply

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

*

* Copy This Password *

* Type Or Paste Password Here *

43,751 Spam Comments Blocked so far by Spam Free Wordpress

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=""> <s> <strike> <strong>