a lot of you want to know how to make a context menu for a ListView. PlusMinus alread did such a tutorial, but his version is only for SDKs prior to v1.0. So I'll make a new one you all can use.
Using java Syntax Highlighting
- class MyActivity extends Activity {
- protected static final int CONTEXT_CLICK_ME = Menu.FIRST;
- public void onCreate(Bundle savedInstanceState){
- super(savedInstanceState);
- setContentView(R.layout.main);
- listView = (ListView)findViewById(R.id.listView);
- // Some cursor adapter
- Cursor c = this.managedQuery(uri, null, null, null, null);
- SimpleCursorAdapter listAdapter = new SimpleCursorAdapter(this, c);
- mList.setAdapter(listAdapter );
- // This will make the listView create a ContextMenu when you long press it.
- // It also create the awsome menu option "Click Me"
- listView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
- @Override
- public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
- menu.add(0, CONTEXT_CLICK_ME, 0, "Click Me");
- }
- });
- }
- public boolean onContextItemSelected(MenuItem item) {
- switch (item.getItemId()) {
- case CONTEXT_CLICK_ME:
- // This is actually where the magic happens.
- // As we use an adapter view (which the ListView is)
- // We can cast item.getMenuInfo() to AdapterContextMenuInfo
- AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
- // To get the id of the clicked item in the list use menuInfo.id
- Log.d(TAG, "list pos:"+menuInfo.position+" id:"+menuInfo.id);
- break;
- default:
- return super.onContextItemSelected(item);
- }
- return true;
- }
- }
Parsed in 0.035 seconds, using GeSHi 1.0.8.4





