安卓中显示上下文的Menu的方法
时间: 2023-10-06 20:11:42 浏览: 56
在 Android 中,您可以使用以下代码在任何视图上显示上下文菜单:
1. 在您的 Activity 中,重写 onCreateContextMenu() 方法,设置菜单项:
```java
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
```
2. 在视图上调用 registerForContextMenu() 方法:
```java
TextView textView = findViewById(R.id.text_view);
registerForContextMenu(textView);
```
3. 创建菜单 XML 文件:在 res/menu/ 目录下创建一个名为 context_menu.xml 的文件,并添加菜单项:
```xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/menu_item_1"
android:title="菜单项1" />
<item
android:id="@+id/menu_item_2"
android:title="菜单项2" />
<item
android:id="@+id/menu_item_3"
android:title="菜单项3" />
</menu>
```
4. 处理菜单项的点击事件:覆盖 onContextItemSelected() 方法:
```java
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_1:
// 处理菜单项 1 的点击事件
return true;
case R.id.menu_item_2:
// 处理菜单项 2 的点击事件
return true;
case R.id.menu_item_3:
// 处理菜单项 3 的点击事件
return true;
default:
return super.onContextItemSelected(item);
}
}
```
这样,当用户长按视图时,就会弹出上下文菜单,您可以在菜单中添加所需的菜单项,当用户点击菜单项时,框架会自动调用 onContextItemSelected() 方法。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)