一、菜单概述
菜单在安卓应用程序中占有比较重要的位置。原生安卓提供了三种类型的菜单:选项菜单(OptionsMenu)、上下文菜单(ContextMenu)和子菜单(SubMenu)。在实际安卓项目中,往往会使用SlidingMenu(滑动菜单),但是要求我们学习如何使用第三方开源库。
二、选项菜单案例演示
- 选项菜单针对整个应用程序,提供的是全局性的功能选项。
1、创建安卓应用
(一)、创建安卓应用【OptionsMenuDemo】
(二)将背景图片拷贝到drawable目录
(三)字符串资源文件strings.xml
<resources>
<string name="app_name">选项菜单演示</string>
</resources>
(四)主布局资源文件activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background"
android:gravity="center"
tools:context=".MainActivity">
</LinearLayout>
(五)主界面类 - MainActivity
- 声明菜单标识常量
- 创建选项菜单
- 创建菜单项选择事件方法
(六)演示结果
三、上下文菜单案例演示
- 对不同控件注册不同的上下文菜单,长按控件弹出属于该控件的上下文菜单。
1、创建安卓应用【ContextMenuDemo】
2、将图片素材拷贝到drawable目录
3、字符串资源文件strings.xml
<resources>
<string name="app_name">上下文菜单演示</string>
<string name="file">文件</string>
<string name="edit">编辑</string>
</resources>
4、主布局资源文件acitivity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp"
android:background="#eeeeee">
<TextView
android:id="@+id/tv_file"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="15dp"
android:text="@string/file"
android:textColor="#0000ff"
android:textSize="20sp" />
<TextView
android:id="@+id/tv_edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/edit"
android:textColor="#0000ff"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
5、查看预览效果
5、主界面类 - MainActivity
-
声明变量与常量
-
通过资源标识符获取控件实例
-
给控件注册上下文菜单
-
编写设置图标可用的方法
-
编写创建上下文菜单的方法
-
编写上下文菜单项选择事件处理方法
6、运行结果
7、源代码
package net.ls.contextmenudemo;