menu_main.xml
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:title="添加" android:id="@+id/add"/> <item android:title="删除" android:id="@+id/delete"/> </menu>
MainActivity.java
package com.pingyijinren.helloworld.activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import com.pingyijinren.helloworld.R; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main,menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()){ case R.id.add: Log.d("MainActivity","add"); break; case R.id.delete: Log.d("MainActivity","delete"); break; } return true; } }