1、无需设置布局文件
2、创建一个类,基础Activity
3、重写onOptionsItemSelected方法,在这个方法里面添加菜单项
4、如果需要给菜单项添加单击事件,需要重写onOptionsItemSelected方法
[1].[代码] MenuDemoActivity.java 跳至 [1]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
package
com.yyl;
import
Android.app.Activity;
import
Android.os.Bundle;
import
Android.view.Menu;
import
Android.view.MenuItem;
public
class
MenuDemoActivity
extends
Activity {
public
static
final
int
EIGHT_ID = Menu.FIRST+
1
;
public
static
final
int
SIXTEEN_ID = Menu.FIRST+
2
;
public
static
final
int
TWENTY_FOUR_ID = Menu.FIRST+
3
;
public
static
final
int
TWO_ID = Menu.FIRST+
4
;
public
static
final
int
THIRTY_TWO_ID = Menu.FIRST+
5
;
public
static
final
int
FORTY_ID = Menu.FIRST+
6
;
public
static
final
int
ONE_ID = Menu.FIRST+
7
;
@Override
public
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
//创建OptionsMenu
@Override
public
boolean
onCreateOptionsMenu(Menu menu) {
this
.populateMenu(menu);
return
super
.onCreateOptionsMenu(menu);
}
//单击事件
@Override
public
boolean
onOptionsItemSelected(MenuItem item) {
int
itemId = item.getItemId();
System.out.println(itemId);
return
super
.onOptionsItemSelected(item);
}
private
void
populateMenu(Menu menu) {
menu.add(Menu.NONE, ONE_ID, Menu.NONE,
"1 Pixel"
);
menu.add(Menu.NONE, TWO_ID, Menu.NONE,
"2 Pixels"
);
menu.add(Menu.NONE, EIGHT_ID, Menu.NONE,
"8 Pixels"
);
menu.add(Menu.NONE, SIXTEEN_ID, Menu.NONE,
"16 Pixels"
);
menu.add(Menu.NONE, TWENTY_FOUR_ID, Menu.NONE,
"24 Pixels"
);
menu.add(Menu.NONE, THIRTY_TWO_ID, Menu.NONE,
"32 Pixels"
);
menu.add(Menu.NONE, FORTY_ID, Menu.NONE,
"40 Pixels"
);
}
@Override
public
boolean
onMenuItemSelected(
int
featureId, MenuItem item) {
//得到点击的菜单项的ID(此Id是自己设定的)
int
itemId = item.getItemId();
if
(ONE_ID == itemId)
{
System.out.println(
"您选择了 1 Pixel 菜单"
);
}
return
super
.onMenuItemSelected(featureId, item);
}
}
|