Creating a ContextMenu on a ListView

Basic Tutorials concerning: GUI, Views, Activites, XML, Layouts, Intents, ...

Creating a ContextMenu on a ListView

Postby plusminus » Sun Jun 15, 2008 3:18 pm

Creating a ContextMenu on a ListView


What you learn: You will learn how to create a ContextMenu on a ListView. This can easily be applied to other situations.
Difficulty: 2 of 5 :)

:idea: Questions/Problems: Simply post below...

What it will look like:
Image


Description:
The Context-Menu gets visible when long-pressing an entry in the ListView.
Layout: "/res/main.xml"
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.         android:orientation="vertical"
  4.         android:layout_width="fill_parent"
  5.         android:layout_height="fill_parent">
  6.         <TextView
  7.                 android:layout_width="fill_parent"
  8.                 android:layout_height="wrap_content"
  9.                 android:text="Long-Press on of the Items in the list." />
  10.         <ListView android:id="@+id/list_favorites"
  11.                 android:layout_width="fill_parent"
  12.                 android:layout_height="fill_parent"/>
  13. </LinearLayout>
Parsed in 0.002 seconds, using GeSHi 1.0.8.4


We will create a ListView that gets filled by a list of a custom Class (Favorite). In the ContextMenu we will offer the user a possibility to delete the entry he long-pressed.
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package org.anddev.contextmenusample;
  2.  
  3. import java.util.ArrayList;
  4.  
  5. import android.app.Activity;
  6. import android.os.Bundle;
  7. import android.view.ContextMenu;
  8. import android.view.View;
  9. import android.view.Menu.Item;
  10. import android.view.View.OnPopulateContextMenuListener;
  11. import android.widget.ArrayAdapter;
  12. import android.widget.ListView;
  13. import android.widget.AdapterView.ContextMenuInfo;
  14.  
  15. public class ContextMenuSample extends Activity {
  16.  
  17.         // ===========================================================
  18.         // Final Fields
  19.         // ===========================================================
  20.         protected static final int CONTEXTMENU_DELETEITEM = 0;
  21.  
  22.         // ===========================================================
  23.         // Fields
  24.         // ===========================================================
  25.  
  26.         protected ListView mFavList;
  27.         protected ArrayList<Favorite> fakeFavs = new ArrayList<Favorite>();
  28.  
  29.         // ===========================================================
  30.         // "Constructors"
  31.         // ===========================================================
  32.  
  33.         /** Called when the activity is first created. */
  34.         @Override
  35.         public void onCreate(Bundle icicle) {
  36.                 super.onCreate(icicle);
  37.                 setContentView(R.layout.main);
  38.  
  39.                 /* Add some items to the list the listview will be showing. */
  40.                 fakeFavs.add(new Favorite("John", "nice guy"));
  41.                 fakeFavs.add(new Favorite("Yasmin", "hot girl"));
  42.                 fakeFavs.add(new Favorite("Jack", "cool guy"));
  43.  
  44.                 this.mFavList = (ListView) this.findViewById(R.id.list_favorites);
  45.                 initListView();
  46.         }
  47.  
  48.         private void refreshFavListItems() {
  49.                 mFavList.setAdapter(new ArrayAdapter<Favorite>(this,
  50.                                 android.R.layout.simple_list_item_1, fakeFavs));
  51.         }
  52.  
  53.         private void initListView() {
  54.                 /* Loads the items to the ListView. */
  55.                 refreshFavListItems();
  56.  
  57.                 /* Add Context-Menu listener to the ListView. */
  58.                 mFavList.setOnPopulateContextMenuListener(new OnPopulateContextMenuListener() {
  59.  
  60.                         @Override
  61.                         public void onPopulateContextMenu(ContextMenu conMenu, View arg1, Object arg2) {
  62.                                 conMenu.setHeader("ContextMenu");
  63.                                 conMenu.add(0, CONTEXTMENU_DELETEITEM, "Delete this favorite!");
  64.                                 /* Add as many context-menu-options as you want to. */
  65.                         }
  66.                 });
  67.         }
  68.  
  69.         // ===========================================================
  70.         // Methods from SuperClass/Interfaces
  71.         // ===========================================================
  72.  
  73.         @Override
  74.         public boolean onContextItemSelected(Item aItem) {
  75.                 ContextMenuInfo menuInfo = (ContextMenuInfo) aItem.getMenuInfo();
  76.  
  77.                 /* Switch on the ID of the item, to get what the user selected. */
  78.                 switch (aItem.getId()) {
  79.                         case CONTEXTMENU_DELETEITEM:
  80.                                 /* Get the selected item out of the Adapter by its position. */
  81.                                 Favorite favContexted = (Favorite) mFavList.getAdapter()
  82.                                         .getItem(menuInfo.position);
  83.                                 /* Remove it from the list.*/
  84.                                 fakeFavs.remove(favContexted);
  85.  
  86.                                 refreshFavListItems();
  87.                                 return true; /* true means: "we handled the event". */
  88.                 }
  89.                 return false;
  90.         }
  91.  
  92.         // ===========================================================
  93.         // Inner and Anonymous Classes
  94.         // ===========================================================
  95.  
  96.         /** Small class holding some basic */
  97.         protected class Favorite {
  98.  
  99.                 protected String name;
  100.                 protected String kindness;
  101.  
  102.                 protected Favorite(String name, String kindness) {
  103.                         this.name = name;
  104.                         this.kindness = kindness;
  105.                 }
  106.  
  107.                 /** The ListView is going to display the toString() return-value! */
  108.                 public String toString() {
  109.                         return name + " (" + kindness + ")";
  110.                 }
  111.  
  112.                 public boolean equals(Object o) {
  113.                         return o instanceof Favorite && ((Favorite) o).name.compareTo(name) == 0;
  114.                 }
  115.         }
  116. }
Parsed in 0.043 seconds, using GeSHi 1.0.8.4

That's it :)

Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Top

Postby shiteiru » Tue Jun 17, 2008 7:42 pm

is there a way to open the context menu with just a single normal click?

right now you have to press an item long to get the contextmenu.
shiteiru
Junior Developer
Junior Developer
 
Posts: 23
Joined: Tue May 20, 2008 7:16 pm

Postby phannguyen » Wed Oct 08, 2008 4:24 am

hi plusminus,
i create a menu context on mapview like this:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. public class TrackingMapActivity extends MapActivity
  2.  
  3. {
  4.  
  5.                      
  6.  
  7.     // Identifiers for our menu items.
  8.  
  9.     private static final int STARTTRACK_ID_CM = Menu.FIRST ;
  10.  
  11.     private static final int SAT_ID_CM = Menu.FIRST+1;
  12.  
  13.     private static final int ZIN_ID_CM = Menu.FIRST + 2;
  14.  
  15.     private static final int ZOUT_ID_CM = Menu.FIRST + 3;
  16.  
  17.    
  18.  
  19.       private static TrackingViewer mMapView;
  20.  
  21.  
  22.  
  23.        
  24.  
  25.     /** Called when the activity is first created. */
  26.  
  27.     @Override
  28.  
  29.     public void onCreate(Bundle icicle) {
  30.  
  31.         super.onCreate(icicle);
  32.  
  33.        
  34.  
  35.         setContentView(R.layout.map);
  36.  
  37.      // Get the map view from resource file
  38.  
  39.         mMapView = (TrackingViewer)findViewById(R.id.mv);
  40.  
  41.         mMapView.setSatellite(false);
  42.  
  43.        
  44.  
  45.         mMapView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
  46.  
  47.             public void  onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)  {
  48.  
  49.                
  50.  
  51.                 //Let the menu appear
  52.  
  53.                   menu.add(Menu.NONE, STARTTRACK_ID_CM,1, R.string.menu_track);
  54.  
  55.                   menu.add(Menu.NONE, SAT_ID_CM,2, R.string.menu_sat);
  56.  
  57.                   menu.add(Menu.NONE, ZIN_ID_CM,3, R.string.menu_zin);
  58.  
  59.                   menu.add(Menu.NONE, ZOUT_ID_CM,4, R.string.menu_zout);    
  60.  
  61.             }
  62.  
  63.                        
  64.  
  65.         });
  66.  
  67. }
Parsed in 0.035 seconds, using GeSHi 1.0.8.4

although i have pressed left mouse for a long time ,but menu context not appear.
what do i wrong here?
please show me,thanks a lot.
PhanNguyen
phannguyen
Experienced Developer
Experienced Developer
 
Posts: 56
Joined: Thu Jul 17, 2008 7:37 am

Postby plusminus » Wed Oct 08, 2008 5:02 am

Hi phannguyen,

MapView handles stuff a bit different :roll:

So I put some code to the snippet-section, that works fine for AndNav:
:arrow: mapview_longpress_gesturedetector_ontouchlistener-t3071.html

Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Postby phannguyen » Wed Oct 08, 2008 9:31 am

thanks plusminus, now i get it.
but i want to get event about double touch on mapview,how can i do that?

regard.
PhanNguyen
phannguyen
Experienced Developer
Experienced Developer
 
Posts: 56
Joined: Thu Jul 17, 2008 7:37 am

Postby happy_bob » Mon Oct 20, 2008 3:13 pm

Hi!

I get the following error messages and i don't know what i'm doing wrong.



The import android.view.Menu.Item cannot be resolved
The import android.view.View.OnPopulateContextMenuListener cannot be resolved
The import android.widget.AdapterView.ContextMenuInfo cannot be resolved
happy_bob
Freshman
Freshman
 
Posts: 3
Joined: Mon Oct 20, 2008 2:51 pm

Top

Postby miguelo » Mon Nov 17, 2008 4:10 pm

Hi,

I have a little problen with my ContextMenus...what is the best way to destroy the PopupMenu when the user touch on screen outside of it???

Thanks and regards,

miguelo.
miguelo
Freshman
Freshman
 
Posts: 6
Joined: Mon Nov 17, 2008 4:05 pm

Postby Ventrix » Fri Mar 20, 2009 4:00 pm

is setOnPopulateContextMenuListener deprecated?
http://www.androidgreece.gr - Greek Android Community
User avatar
Ventrix
Junior Developer
Junior Developer
 
Posts: 11
Joined: Tue Mar 04, 2008 11:47 pm
Location: Greece

I can not to run with new sdk:(

Postby laji1110 » Fri Apr 17, 2009 5:53 am

I am using android sdk 1.0 r2.

There are many problem in program.

Help me to convert it to suite new sdk, plz!

Many thanks!
laji1110
Freshman
Freshman
 
Posts: 5
Joined: Wed Mar 18, 2009 10:10 pm

Postby WarrenFaith » Fri Apr 17, 2009 10:20 am

Well, maybe you should update to sdk 1.1 before start porting the code... or you have to do it twice...

what error exactly do you have? my crystal ball doesn't work today...
WarrenFaith
Moderator
Moderator
 
Posts: 227
Joined: Fri Mar 13, 2009 10:59 am
Location: Berlin, Germany

Hi WarrenFaith

Postby laji1110 » Sat Apr 18, 2009 3:57 am

Yeah, i have updated SDK 1.1 but the the problem is still there
Attachments
ContextMenuSample.zip
(29.83 KiB) Downloaded 661 times
laji1110
Freshman
Freshman
 
Posts: 5
Joined: Wed Mar 18, 2009 10:10 pm

Hi all!

Postby laji1110 » Sun May 10, 2009 5:23 pm

I've just found the way to solve!

So, the Android SDK is changing so fast:D

Thanks all


Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package org.anddev.contextmenusample;
  2.  
  3.  
  4.  
  5. import java.util.ArrayList;
  6.  
  7.  
  8.  
  9. import android.app.Activity;
  10.  
  11. import android.os.Bundle;
  12.  
  13. import android.util.Log;
  14.  
  15. import android.view.ContextMenu;
  16.  
  17. import android.view.View;
  18.  
  19. import android.view.MenuItem;
  20.  
  21. import android.view.ContextMenu.ContextMenuInfo;
  22.  
  23. import android.view.View.OnCreateContextMenuListener;
  24.  
  25. import android.view.View.OnLongClickListener;
  26.  
  27. import android.widget.AdapterView;
  28.  
  29. import android.widget.ArrayAdapter;
  30.  
  31. import android.widget.ListView;
  32.  
  33. import android.widget.AdapterView.AdapterContextMenuInfo;
  34.  
  35. import android.widget.AdapterView.OnItemLongClickListener;
  36.  
  37.  
  38.  
  39. public class ContextMenuSample extends Activity{
  40.  
  41.  
  42.  
  43.      // ===========================================================
  44.  
  45.      // Final Fields
  46.  
  47.      // ===========================================================
  48.  
  49.      protected static final int CONTEXTMENU_DELETEITEM = 0;
  50.  
  51.  
  52.  
  53.      // ===========================================================
  54.  
  55.      // Fields
  56.  
  57.      // ===========================================================
  58.  
  59.  
  60.  
  61.      protected ListView mFavList;
  62.  
  63.      protected ArrayList<Favorite> fakeFavs = new ArrayList<Favorite>();
  64.  
  65.  
  66.  
  67.      // ===========================================================
  68.  
  69.      // "Constructors"
  70.  
  71.      // ===========================================================
  72.  
  73.  
  74.  
  75.      /** Called when the activity is first created. */
  76.  
  77.      @Override
  78.  
  79.      public void onCreate(Bundle icicle) {
  80.  
  81.           super.onCreate(icicle);
  82.  
  83.           setContentView(R.layout.main);
  84.  
  85.  
  86.  
  87.           /* Add some items to the list the listview will be showing. */
  88.  
  89.           fakeFavs.add(new Favorite("John", "nice guy"));
  90.  
  91.           fakeFavs.add(new Favorite("Yasmin", "hot girl"));
  92.  
  93.           fakeFavs.add(new Favorite("Jack", "cool guy"));
  94.  
  95.  
  96.  
  97.           this.mFavList = (ListView) this.findViewById(R.id.list_favorites);
  98.  
  99.           initListView();
  100.  
  101.      }
  102.  
  103.  
  104.  
  105.      private void refreshFavListItems() {
  106.  
  107.           mFavList.setAdapter(new ArrayAdapter<Favorite>(this,
  108.  
  109.                     android.R.layout.simple_list_item_1, fakeFavs));
  110.  
  111.      }
  112.  
  113.  
  114.  
  115.      private void initListView() {
  116.  
  117.           /* Loads the items to the ListView. */
  118.  
  119.           refreshFavListItems();
  120.  
  121.  
  122.  
  123.           /* Add Context-Menu listener to the ListView. */
  124.  
  125.           //mFavList.setOnItemLongClickListener();
  126.  
  127.           mFavList.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
  128.  
  129.  
  130.  
  131.                         @Override
  132.  
  133.                         public void onCreateContextMenu(ContextMenu menu, View v,
  134.  
  135.                                         ContextMenuInfo menuInfo) {
  136.  
  137.                                 // TODO Auto-generated method stub
  138.  
  139.                                 menu.setHeaderTitle("ContextMenu");
  140.  
  141.                 menu.add(0, CONTEXTMENU_DELETEITEM,0, "Delete this favorite!");
  142.  
  143.                                
  144.  
  145.                         }
  146.  
  147.  
  148.  
  149.              
  150.  
  151.          });
  152.  
  153.           /*mFavList.setOnItemLongClickListener( new AdapterView.OnItemLongClickListener
  154.  
  155.                           (){
  156.  
  157.                           @Override
  158.  
  159.                           public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {
  160.  
  161.                                   Log.i("Debug", "Log id "+id+" pos "+pos);
  162.  
  163.                                   return false;
  164.  
  165.                           }
  166.  
  167.                           });
  168.  
  169.            */
  170.  
  171.            
  172.  
  173.      }
  174.  
  175.  
  176.  
  177.      // ===========================================================
  178.  
  179.      // Methods from SuperClass/Interfaces
  180.  
  181.      // ===========================================================
  182.  
  183.  
  184.  
  185.      @Override
  186.  
  187.      public boolean onContextItemSelected(MenuItem aItem) {
  188.  
  189.           AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) aItem.getMenuInfo();
  190.  
  191.  
  192.  
  193.           /* Switch on the ID of the item, to get what the user selected. */
  194.  
  195.           switch (aItem.getItemId()) {
  196.  
  197.                case CONTEXTMENU_DELETEITEM:
  198.  
  199.                     /* Get the selected item out of the Adapter by its position. */
  200.  
  201.                     Favorite favContexted = (Favorite) mFavList.getAdapter()
  202.  
  203.                          .getItem(menuInfo.position);
  204.  
  205.                     /* Remove it from the list.*/
  206.  
  207.                     fakeFavs.remove(favContexted);
  208.  
  209.  
  210.  
  211.                     refreshFavListItems();
  212.  
  213.                     return true; /* true means: "we handled the event". */
  214.  
  215.           }
  216.  
  217.           return false;
  218.  
  219.      }
  220.  
  221.  
  222.  
  223.      // ===========================================================
  224.  
  225.      // Inner and Anonymous Classes
  226.  
  227.      // ===========================================================
  228.  
  229.  
  230.  
  231.      /** Small class holding some basic */
  232.  
  233.      protected class Favorite {
  234.  
  235.  
  236.  
  237.           protected String name;
  238.  
  239.           protected String kindness;
  240.  
  241.  
  242.  
  243.           protected Favorite(String name, String kindness) {
  244.  
  245.                this.name = name;
  246.  
  247.                this.kindness = kindness;
  248.  
  249.           }
  250.  
  251.  
  252.  
  253.           /** The ListView is going to display the toString() return-value! */
  254.  
  255.           public String toString() {
  256.  
  257.                return name + " (" + kindness + ")";
  258.  
  259.           }
  260.  
  261.  
  262.  
  263.           public boolean equals(Object o) {
  264.  
  265.                return o instanceof Favorite && ((Favorite) o).name.compareTo(name) == 0;
  266.  
  267.           }
  268.  
  269.      }
  270.  
  271. }
  272.  
  273.                  
  274.  
  275.                
Parsed in 0.053 seconds, using GeSHi 1.0.8.4
Attachments
ContextMenuSample.zip
(31.58 KiB) Downloaded 859 times
laji1110
Freshman
Freshman
 
Posts: 5
Joined: Wed Mar 18, 2009 10:10 pm

Postby mccarthycw » Fri Jul 17, 2009 5:43 pm

I have tried multiple times to get a context menu working in this fashion albeit failing. I think later today I will just make a new listactivity class and attempt to get it working. This way seems to not work no matter what I do.
mccarthycw
Freshman
Freshman
 
Posts: 4
Joined: Fri Jul 17, 2009 5:40 pm
Location: Mechanicsburg, Pennsylvania, USA

Postby mccarthycw » Fri Jul 17, 2009 6:03 pm

BTW, I do understand the original post is depracated. I have tried what laji1110 has submitted.
mccarthycw
Freshman
Freshman
 
Posts: 4
Joined: Fri Jul 17, 2009 5:40 pm
Location: Mechanicsburg, Pennsylvania, USA

Postby qlimax » Wed Oct 07, 2009 11:45 pm

thank you for this tutorial (and updates)! :)

big up!
¯`·.¸¸.><((((º>¯`·.¸¸. ><((((º>
User avatar
qlimax
Master Developer
Master Developer
 
Posts: 271
Joined: Mon Aug 31, 2009 10:54 am
Location: Swiss

Top
Next

Return to Novice Tutorials

Who is online

Users browsing this forum: Yahoo [Bot] and 8 guests