package com.example.dell.caidanxiang; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.Toast; public class optionmenu extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_optionmenu); } @Override public boolean onCreateOptionsMenu(Menu menu) { //纯编码格式 // menu.add(1,1,0,"添加"); // menu.add(1,2,1,"删除"); // menu.add(1,3,2,"修改"); //加载菜单文件格式 MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.mymenu,menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { Toast.makeText(optionmenu.this, "选项是"+ item, Toast.LENGTH_SHORT).show(); return super.onOptionsItemSelected(item); } }
纯编码格式(代码中注释部分)不需要加载下面菜单文件
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/it1"
android:title="添加"
></item>
<item android:id="@+id/it2"
android:title="修改"
></item>
</menu>