main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello,This is Andy's Blog!"/>
<ListView
android:id="@+id/lv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
cmenu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/add" android:title="增加"/>
<item android:id="@+id/update" android:title="更新"/>
<item android:id="@+id/delete" android:title="删除"/>
</menu>
MenuActivity.java
package com.andyidea.menudemo;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MenuActivity extends Activity {
ListView lv;
private ArrayAdapter<String> adapter;
private List<String> alist = new ArrayList<String>();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView)findViewById(R.id.lv);
alist.add("第一");
alist.add("第二");
alist.add("第三");
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,alist);
lv.setAdapter(adapter);
//注册视图对象,即为ListView控件注册上下文菜单
registerForContextMenu(lv);
}
/**
* 创建上下文菜单选项
*/
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
//1.通过手动添加来配置上下文菜单选项
//menu.add(0, 1, 0, "修改");
//menu.add(0, 2, 0, "删除");
//2.通过xml文件来配置上下文菜单选项
MenuInflater mInflater = getMenuInflater();
mInflater.inflate(R.menu.cmenu, menu);
super.onCreateContextMenu(menu, v, menuInfo);
}
/**
* 当菜单某个选项被点击时调用该方法
*/
@Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()){
case 1:
Toast.makeText(this, "你选择了手动修改", Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(this, "你选择了手动删除", Toast.LENGTH_SHORT).show();
break;
case R.id.add:
Toast.makeText(this, "你选择了XML增加", Toast.LENGTH_SHORT).show();
break;
case R.id.update:
Toast.makeText(this, "你选择了XML更新", Toast.LENGTH_SHORT).show();
break;
case R.id.delete:
Toast.makeText(this, "你选择了XML删除", Toast.LENGTH_SHORT).show();
break;
}
return super.onContextItemSelected(item);
}
/**
* 当上下文菜单关闭时调用的方法
*/
@Override
public void onContextMenuClosed(Menu menu) {
// TODO Auto-generated method stub
super.onContextMenuClosed(menu);
}
}