xml文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_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"
tools:context="com.example.menudemo.OptionMenuDemo" > <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" /> </RelativeLayout>
源代码:
package com.example.menudemo; import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
/**
* 选项菜单:optionMenu
*
* 创建选项菜单:重写onCreateMenu()
* |--设置菜单项
* 可用代码动态设置menu.add()
* 还可通过xml设置MenuInflater.inflate()
* |--设置菜单项点击事件:onOptionsItemSelected()
* @author Administrator
*
*/
public class OptionMenuDemo extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present. //通过xml加载布局文件的形式创建菜单
//getMenuInflater().inflate(R.menu.main, menu); MenuItem item = menu.add(1, 1, 1, "menu1");
item.setTitle("高级 menu");
item.setIcon(R.drawable.ic_launcher);//api>=11不显示图标
menu.add(1, 2, 1, "menu2");
menu.add(1, 3, 1, "menu3");
menu.add(1, 4, 1, "menu4");
menu.add(1, 5, 1, "menu5");
return true;
} @Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
/*case R.id.menu1:
Toast.makeText(this, "clicked menu1", Toast.LENGTH_SHORT).show();
break;
case R.id.menu2:
Toast.makeText(this, "clicked menu2", Toast.LENGTH_SHORT).show();
break;*/
case 1:{
//点击菜单1跳转到第二个页面
Intent intent = new Intent(this,SecondActivity.class);
item.setIntent(intent);
Toast.makeText(this, "clicked menu1", Toast.LENGTH_SHORT).show();
break;
}
case 2:
Toast.makeText(this, "clicked menu2", Toast.LENGTH_SHORT).show();
break;
case 3:
Toast.makeText(this, "clicked menu3", Toast.LENGTH_SHORT).show();
break;
case 4:
Toast.makeText(this, "clicked menu4", Toast.LENGTH_SHORT).show();
break;
case 5:
Toast.makeText(this, "clicked menu5", Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}
}