菜单文件

1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@+id/exit"
android:title="退出"/>
<item android:id="@+id/set"
android:title="设置"/>
<item android:id="@+id/account"
android:title="账号"/>
</menu>

代码文件

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
package com.example.menutest03;

import android.app.Activity;import android.os.Bundle;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.Toast;


public class MainActivity extends Activity implements OnClickListener,OnMenuItemClickListener{


private Button button1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
}

//点击按钮后,加载弹出式菜单
@Override
public void onClick(View v) {
//创建弹出式菜单对象(最低版本11)
PopupMenu popup = new PopupMenu(this, v);//第二个参数是绑定的那个view
//获取菜单填充器
MenuInflater inflater = popup.getMenuInflater();
//填充菜单
inflater.inflate(R.menu.main, popup.getMenu());
//绑定菜单项的点击事件
popup.setOnMenuItemClickListener(this);
//显示(这一行代码不要忘记了)
popup.show();

}

//弹出式菜单的单击事件处理
@Override
public boolean onMenuItemClick(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.exit:
Toast.makeText(this, "退出", Toast.LENGTH_SHORT).show();
break;
case R.id.set:
Toast.makeText(this, "设置", Toast.LENGTH_SHORT).show();
break;
case R.id.account:
Toast.makeText(this, "账号", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
return false;
}

}