android手机右上角的菜单Menu例子
1、activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:id="@+id/root"
tools:context="com.example.ff.MainActivity" >
</RelativeLayout>
2、MainActivity.java
package com.example.ff;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class MainActivity extends Activity {
RelativeLayout root;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
root = (RelativeLayout) findViewById(R.id.root);
//注册上下文菜单
super.registerForContextMenu(root);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//一级菜单
menu.add("打开");
menu.add("添加");
menu.add("电话");
menu.add("保存");
//添加子菜单
SubMenu editItem = menu.addSubMenu("编辑");
//二级菜单
editItem.add("复制");
editItem.add("剪切");
editItem.add("粘贴");
menu.add("暂停");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Toast.makeText(MainActivity.this, "你选中了"+item.getTitle(),
Toast.LENGTH_LONG).show();
return true;
}
}