Use Context menu to control ListView
Description
The following code shows how to Use Context menu to control ListView.
Example
Menu main.xml file
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/menu_delete"
android:icon="@android:drawable/ic_menu_delete"
android:title="Delete Item"
/>
<item
android:id="@+id/menu_edit"
android:icon="@android:drawable/ic_menu_edit"
android:title="Edit Item"
/>
</menu>
Activity Java code
package com.java2s.myapplication3.app;
/*from w w w . j a va2s . c o m*/
import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
private static final String[] ITEMS =
{"CSS", "HTML", "Javascript", "SQL", "Java", "Android"};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView list = new ListView(this);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, ITEMS);
list.setAdapter(adapter);
registerForContextMenu(list);
setContentView(list);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.main, menu);
menu.setHeaderTitle("Choose an Option");
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
int listPosition = info.position;
switch(item.getItemId()) {
case R.id.menu_delete:
//Perform delete actions
break;
case R.id.menu_edit:
//Perform edit actions
break;
default:
return super.onContextItemSelected(item);
}
return true;
}
}