1 import java.lang.reflect.Method; 2 3 import android.os.Bundle; 4 import android.provider.Settings; 5 import android.app.Activity; 6 import android.content.Intent; 7 import android.view.Menu; 8 import android.view.MenuItem; 9 import android.widget.TextView; 10 11 public class MainActivity extends Activity { 12 private TextView textView; 13 @Override 14 protected void onCreate(Bundle savedInstanceState) { 15 super.onCreate(savedInstanceState); 16 setContentView(R.layout.activity_main); 17 18 textView = (TextView) findViewById(R.id.textView); 19 } 20 //创建系统菜单 21 //menu接收的是系统创建的菜单对象 22 @Override 23 public boolean onCreateOptionsMenu(Menu menu) { 24 setIconEnable(menu,true);//让菜单项显示图标 25 // 创建系统菜单 26 getMenuInflater().inflate(R.menu.main, menu); 27 return true; 28 } 29 //选择系统菜单中某个菜单项的事件监听 30 //item接收的是被选择的菜单项对象 31 @Override 32 public boolean onOptionsItemSelected(MenuItem item) { 33 // TODO 添加事件监听 34 switch(item.getItemId()) 35 { 36 case R.id.action_settings: 37 startActivity(new Intent(Settings.ACTION_SETTINGS)); 38 break; 39 case R.id.action_add: 40 textView.setTextSize(textView.getTextSize()+5); 41 break; 42 case R.id.action_sub: 43 textView.setTextSize(textView.getTextSize()-5); 44 break; 45 } 46 return super.onOptionsItemSelected(item); 47 } 48 49 50 //为系统菜单项添加图标 51 //enable为true时,菜单添加图标有效,enable为false时无效。4.0+系统默认无效 52 private void setIconEnable(Menu menu, boolean enable) 53 { 54 try 55 { 56 Class<?> clazz = Class.forName("com.android.internal.view.menu.MenuBuilder"); 57 Method m = clazz.getDeclaredMethod("setOptionalIconsVisible", boolean.class); 58 m.setAccessible(true); 59 //MenuBuilder实现Menu接口,创建菜单时,传进来的menu其实就是MenuBuilder对象(java的多态特征) 60 m.invoke(menu, enable); 61 62 } catch (Exception e) 63 { 64 e.printStackTrace(); 65 } 66 } 67 68 69 70 }
MainActivity
1 <menu xmlns:android="http://schemas.android.com/apk/res/android" > 2 <!-- 3 一个item就是一个菜单项,android:showAsAction="never"属性设置是否是动作项 4 动作项: 5 --> 6 <item 7 android:id="@+id/action_settings" 8 android:orderInCategory="100" 9 android:icon="@android:drawable/ic_menu_help" 10 android:showAsAction="never" 11 android:title="@string/action_settings"/> 12 <item 13 android:id="@+id/action_add" 14 android:orderInCategory="101" 15 android:icon="@android:drawable/ic_menu_add" 16 android:showAsAction="never" 17 android:title="放大字体"/> 18 <item 19 android:id="@+id/action_sub" 20 android:orderInCategory="101" 21 android:icon="@android:drawable/ic_menu_delete" 22 android:showAsAction="never" 23 android:title="缩小字体"/> 24 25 </menu>
menu_main
时间: 2024-10-12 22:45:06