- 在
res
目录下新建menu
目录,用于放置菜单布局文件(右键res
->new
->Android Resource Directory
->menu
)
- 在
menu
下创建菜单布局文件,根标签为menu
,menu
下面有多个group
,group
下面有多个item
.
简单示例如下:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/oi_1"
android:title="编程语言"
android:checkable="true"></item>
<item
android:id="@+id/oi_2"
android:checkable="true"
android:title="算法"></item>
</menu>
- 重写
Activity
的onCreateOptionsMenu
方法
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//根据菜单布局文件填充菜单项
getMenuInflater().inflate(R.menu.menu_options, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.oi_1:
doSomething....
return true;
case R.id.oi_2:
doSomething....
return true;
case R.id.oi_3:
doSomething....
return true;
case R.id.oi_4:
doSomething....
return true;
default:
doSomething....
return super.onOptionsItemSelected(item);
}
}
二、上下文菜单
- 创建菜单布局文件
- 为指定view(可以是Button,TextView等等)注册上下文菜单
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_context_menu);
//这是一个按钮
Button colorSelector = findViewById(R.id.btn_color_selector);
//为button注册上下文菜单
registerForContextMenu(colorSelector);
}
- 重写
Activity
的onCreateOptionsMenu
方法
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
//为菜单设置title
menu.setHeaderTitle("please select your favorite color:");
//填充菜单项
getMenuInflater().inflate(R.menu.menu_context, menu);
}
@Override
public boolean onContextItemSelected(@NonNull MenuItem item) {
switch(item.getItemId()){
case R.id.ci_red:
colorSelector.setBackgroundColor(Color.parseColor("red"));
return true;
case R.id.ci_purple:
colorSelector.setBackgroundColor(Color.parseColor("purple"));
return true;
case R.id.ci_white:
colorSelector.setBackgroundColor(Color.parseColor("white"));
return true;
}
return super.onContextItemSelected(item);
}
@Override
protected void onDestroy() {
super.onDestroy();
//取消注册,防止内存溢出
unregisterForContextMenu(colorSelector);
}
三、弹出式菜单
- 创建菜单布局文件
- 监听指定view点击事件,同时构建弹出菜单对象
//这是对应button的点击监听事件
public void showPopupMenu(View view) {
final PopupMenu menu = new PopupMenu(PopupMenuActivity.this, view);
getMenuInflater().inflate(R.menu.menu_popup, menu.getMenu());
menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.pi_hide:
//菜单隐藏
menu.dismiss();
return true;
default:
Toast.makeText(PopupMenuActivity.this, item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
}
});
menu.show();
}
Android三种菜单的使用方式