<span style="font-size:32px;">这是在layout下写的</span>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.caidan.MainActivity"
tools:ignore="MergeRootFrame" >
<pre name="code" class="java">
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="74dp"
android:text="上下文菜单" />
</FrameLayout>
这是在menu 下写的
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/star"
android:orderInCategory="100"
android:title="star"/>
<item
android:id="@+id/over"
android:orderInCategory="200"
android:title="over"/>
</menu>
这是在主函数里写的
package com.example.caidan;
import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Button;
import android.widget.Toast;
/**
* 上下文菜单
*
* @author Administrator
*
*/
public class MainActivity2 extends Activity {
private Button bnt1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取BUTTON对象
bnt1 = (Button) findViewById(R.id.button1);
//在Button 上注册上下文菜单
registerForContextMenu(bnt1);
}
// 创建上下文菜单的方法
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
// getMenuInflater的意思是菜单加载器。。用来读取配置的菜单
// 填充选项菜单(读取XML文件,解析,加载到MENU组件上)
getMenuInflater().inflate(R.menu.main2, menu);
}
// 上下文菜单项触发事件
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.star:
Toast.makeText(this, "开始...", Toast.LENGTH_SHORT).show();
break;
case R.id.over:
Toast.makeText(this, "结束...", Toast.LENGTH_SHORT).show();
default:
break;
}
return super.onContextItemSelected(item);
}
}