Sunday, June 27, 2010

Where Is The Poptropica Bumble Bee Costume

Click and Context Menu on ListView

Continuing to play with the ListView, we see how to capture click on items in the list and how to display a context menu on a long click.




Capturing a click on an Item of ListView

Similar to button clicks, you define a listener to click on an item and then binds to the ListView.

In our case we will show a toast with the position and id of clicked (a Toast is a warning that appears in superimposed individually and then disappears).

This code:

 AdapterView.OnItemClickListener mItemListener = new 
OnItemClickListener () {public void
onItemClick (AdapterView parent, View v, int pos, long id) {String st =
"Clicked POS =" + id + " ID = "+ id;
Toast.makeText (getApplicationContext (), st,
Toast.LENGTH_SHORT). show ();

}};
((ListView) findViewById (R.id.taskListView))
. SetOnItemClickListener (mItemListener)


Showing context menu

We want that when you do a long click on a list item appears to be a context menu with the Cancel command, Edit, Delete.

First we define the IDs of the menu commands in the private data of the Activity.

 private static final int CANCEL_ID = Menu.FIRST; 
private static final int EDIT_ID Menu.FIRST = +1;
private static final int DELETE_ID Menu.FIRST = +2;

Then there is the ListView to manage ContextMenu.

 registerForContextMenu (findViewById (R.id.taskListView)); 

Then call override the functions that create the context menu and running the operation.


 @ Override public void 
onCreateContextMenu (ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu (menu, v, menuInfo)
menu.add (0, CANCEL_ID, 0, "Cancel");
menu.add (0, EDIT_ID, 0, "Edit");
menu.add (0, DELETE_ID, 0, "Delete");}


@ Override public boolean
onContextItemSelected (MenuItem item) {info =
AdapterContextMenuInfo (AdapterContextMenuInfo) item.getMenuInfo ();
switch (item.getItemId ()) {case
CANCEL_ID:
return true;
homes EDIT_ID:
Toast.makeText (getApplicationContext (), "info.position =" +
info.position, Toast.LENGTH_SHORT). Show ( )
return true;
homes DELETE_ID:
data.remove (info.position)
adapter.notifyDataSetChanged ();
return true;
default: return
super.onContextItemSelected (item);}

}

As you can see the gate is to immediately close the menu, the Edit view for now a toast with information about the item clicked, performs the cancellation Delete item from the database and notifies the adapter that needs to update the ListView before returning to the main Activity.

0 comments:

Post a Comment