package my.com.testmenu;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class TestmenuActivity extends Activity {
private MenuInflater mi;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mi = new MenuInflater(this);
}
//创建菜单
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
mi.inflate(R.menu.test_menu, menu);
return super.onCreateOptionsMenu(menu);
}
//选择菜单Item
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.about:
aboutAlert("本实例演示的是如何使用XML菜单资源来定义菜单!");
break;
case R.id.exit:
exitAlert("真的要退出吗?");
break;
}
return super.onOptionsItemSelected(item);
}
// 显示对话框
private void exitAlert(String msg){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(msg)
.setCancelable(false)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
return;
}
});
AlertDialog alert = builder.create();
alert.show();
}
// 显示对话框
private void aboutAlert(String msg){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(msg)
.setCancelable(false)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
TestmenuActivity.java
test_Menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:title="File"
android:icon="@drawable/file">
<menu>
<group
android:id="@+id/noncheckable_group"
android:checkableBehavior="none">
<item
android:id="@+id/newFile"
android:title="New"
android:alphabeticShortcut="n"/>
<item
android:id="@+id/openFile"
android:title="Open"
android:alphabeticShortcut="o"/>
<item
android:id="@+id/saveFile"
android:title="Save"
android:alphabeticShortcut="s"/>
</group>
</menu>
</item>
<item android:title="Edit" android:icon="@drawable/edit">
<menu>
<group android:id="@+id/edit_group"
android:checkableBehavior="single">
<item android:id="@+id/cut"
android:title="Cut" />
<item android:id="@+id/copy"
android:title="Copy"/>
<item android:id="@+id/past"
android:title="Past"/>
</group>
</menu>
</item>
<item android:title="Help" android:icon="@drawable/help">
<menu>
<group android:id="@+id/help_group">
<item android:id="@+id/about"
android:title="About" />
<item android:id="@+id/exit"
android:title="Exit" />
</group>
</menu>
</item>
</menu>