Adding Long Click functionality in List View – Context Menus Clicks

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

Now that we are familiar with long clicks and Context Menus that are triggered by them, we must understand that Context Menus are but a kind of menu and just like any other type of menu, their items too are clickable. In fact, if there were no such options the whole purpose of displaying a menu is defeated.

In this post I will show you how to handle clicks on the Context Menu which is a rather simple task. All we need to do is add another method. 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.
  • Register the List View for Context Menu and create the method onCreateContextMenu(). Add the two menu items Edit and Delete.
  • Now just after the onCreateContextMenu() method we define another method on:
    public boolean onContextItemSelected(MenuItem item){
    		if(item.getTitle()=="Edit")Toast.makeText(getApplicationContext(), "Edit Clicked", Toast.LENGTH_LONG).show();
    		if(item.getTitle()=="Delete")Toast.makeText(getApplicationContext(), "Delete Clicked", Toast.LENGTH_LONG).show();
    		return true;
        }
    
  • Save your work and execute it on the device or the emulator.
  • I am just displaying a Toast on the click of the Context Menu item. You can choose to do whatever you want.

LongClick1  LongClick2

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.AdapterContextMenuInfo;
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");
	}

    public boolean onContextItemSelected(MenuItem item){
		if(item.getTitle()=="Edit")Toast.makeText(getApplicationContext(), "Edit Clicked", Toast.LENGTH_LONG).show();
		if(item.getTitle()=="Delete")Toast.makeText(getApplicationContext(), "Delete Clicked", Toast.LENGTH_LONG).show();
		return true;
    }
}
Series Navigation<< Adding Long Click functionality in List View – Context MenusList View using SimpleCursorAdapter – Part I >>

Leave a Reply

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

*

* Copy This Password *

* Type Or Paste Password Here *

43,743 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>