标签:
一:在res中新建一个menu的文件夹,然后在文件夹下面建一个main.xml文件,xml的代码如下
1 <?xml version="1.0" encoding="utf-8"?> 2 <menu xmlns:android="http://schemas.android.com/apk/res/android" > 3 <item 4 android:id="@+id/add_item" 5 android:title="Add"/> 6 <item 7 android:id="@+id/remove_item" 8 android:title="Remove"/>
二:在,MainActivity.java重写onCreateOptionsMenu()方法,在MainActivty.java中重写onOptionsItemSelected()方法,代码如下
1 package menudemo.zhangmeng.com.menudemo; 2 3 import android.support.v7.app.AppCompatActivity; 4 import android.os.Bundle; 5 import android.view.Menu; 6 import android.view.MenuItem; 7 import android.widget.Toast; 8 9 public class MainActivity extends AppCompatActivity { 10 11 @Override 12 protected void onCreate(Bundle savedInstanceState) { 13 super.onCreate(savedInstanceState); 14 setContentView(R.layout.activity_main); 15 } 16 17 @Override 18 public boolean onCreateOptionsMenu(Menu menu) { 19 getMenuInflater().inflate(R.menu.main,menu); 20 return true; 21 } 22 23 @Override 24 public boolean onOptionsItemSelected(MenuItem item) { 25 switch (item.getItemId()){ 26 case R.id.add_item: 27 Toast.makeText(this, "you clicked add", Toast.LENGTH_SHORT).show(); 28 break; 29 case R.id.remove_item: 30 Toast.makeText(this, "you clicked remove", Toast.LENGTH_SHORT).show(); 31 default: 32 } 33 return true; 34 35 } 36 }
标签:
原文地址:http://www.cnblogs.com/WebGiant/p/5898316.html