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 }