ANDROID笔记:利用XML布局文件生成Menu
1 package com.example.android_menu; 2 3 import android.app.Activity; 4 import android.graphics.Color; 5 import android.os.Bundle; 6 import android.view.Menu; 7 import android.view.MenuInflater; 8 import android.view.MenuItem; 9 import android.widget.TextView; 10 11 public class MyMenuActivity extends Activity { 12 TextView textView; 13 14 @Override 15 protected void onCreate(Bundle savedInstanceState) { 16 super.onCreate(savedInstanceState); 17 setContentView(R.layout.contextmenuactivity); 18 textView = (TextView) findViewById(R.id.itemtext); 19 } 20 21 /** 22 * 点击菜单按键时调用的函数 23 */ 24 @Override 25 public boolean onCreateOptionsMenu(Menu menu) { 26 // 菜单加载器 27 MenuInflater menuInflater = new MenuInflater(getApplicationContext()); 28 menuInflater.inflate(R.menu.mymenu, menu); 29 return super.onCreateOptionsMenu(menu); 30 } 31 32 /** 33 * 响应菜单动作的回调函数 34 */ 35 @Override 36 public boolean onOptionsItemSelected(MenuItem item) { 37 //得到Id 38 switch (item.getItemId()) { 39 case R.id.font10sp: 40 textView.setTextSize(10); 41 break; 42 case R.id.font20sp: 43 textView.setTextSize(20); 44 break; 45 case R.id.font30sp: 46 textView.setTextSize(30); 47 break; 48 case R.id.fontblue: 49 textView.setTextColor(Color.BLUE); 50 break; 51 case R.id.fontgreen: 52 textView.setTextColor(Color.GREEN); 53 break; 54 case R.id.fontred: 55 textView.setTextColor(Color.RED); 56 break; 57 } 58 return super.onOptionsItemSelected(item); 59 } 60 }
res/menu/mymenu.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <menu xmlns:android="http://schemas.android.com/apk/res/android" > 3 4 <item 5 android:id="@+id/fontsize" 6 android:title="设置字体大小"> 7 <menu> 8 <!-- 单选 --> 9 <group android:checkableBehavior="single" > 10 <item 11 android:id="@+id/font10sp" 12 android:title="10sp"> 13 </item> 14 <item 15 android:id="@+id/font20sp" 16 android:title="20sp"> 17 </item> 18 <item 19 android:id="@+id/font30sp" 20 android:title="30sp"> 21 </item> 22 </group> 23 </menu> 24 </item> 25 <item 26 android:id="@+id/selectnull" 27 android:title="空白菜单"/> 28 <item 29 android:id="@+id/fontcolor" 30 android:title="设置字体颜色"> 31 <menu> 32 <!-- 多选 --> 33 <group android:checkableBehavior="all" > 34 <item 35 android:id="@+id/fontred" 36 android:title="红色"> 37 </item> 38 <item 39 android:id="@+id/fontgreen" 40 android:title="绿色"> 41 </item> 42 <item 43 android:id="@+id/fontblue" 44 android:title="蓝色"> 45 </item> 46 </group> 47 </menu> 48 </item> 49 50 </menu>
点击Menu按键就会在屏幕底部弹出Menu