
public class Test_Contextmenu extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView txt1 = (TextView) this.findViewById(R.id.txt1);
this.registerForContextMenu(txt1);
TextView txt2 = (TextView) this.findViewById(R.id.txt2);
this.registerForContextMenu(txt2);
}
// 重写 onCreateContextMenu 用以创建上下文菜单
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu, v, menuInfo);
// 创建 R.id.txt1 的上下文菜单
if (v == (TextView) this.findViewById(R.id.txt1)) {
menu.setHeaderIcon(R.drawable.icon);
menu.setHeaderTitle(R.string.titletest);
//menu.clearHeader();
// 第一个参数:组ID
// 第二个参数:菜单项ID
// 第三个参数:顺序号
// 第四个参数:菜单项上显示的内容
menu.add(1,0,0,"菜单1");
menu.add(1,1,1,"菜单2").setCheckable(true); // 增加一个√选项
}
// 创建 R.id.txt2 的上下文菜单(多级)
else if(v == (TextView) this.findViewById(R.id.txt2)){
// ContextMenu.addSubMenu("菜单名称") - 用来添加子菜单。子菜单其实就是一个特殊的菜单
SubMenu sub1 = menu.addSubMenu("父菜单1");
sub1.setHeaderIcon(R.drawable.folder);
sub1.add(0, 0, 0, "菜单1");
sub1.add(0, 1, 1, "菜单2");
sub1.setGroupCheckable(1, true, true);
SubMenu sub2 = menu.addSubMenu("父菜单2");
sub2.setIcon(R.drawable.text);
sub2.add(1, 0, 0, "菜单3");
sub2.add(1, 1, 1, "菜单4");
sub2.setGroupCheckable(1, true, true);
}
}
}

<?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:id="@+id/txt1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="请 长 按 触 发(txt1)"
/>
<TextView
android:id="@+id/txt2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="请 长 按 触 发(txt2)"
/>
</LinearLayout>