【安卓开发】【Android Studio】Menu(菜单栏)的使用及常见问题

一、菜单栏选项

在项目中添加顶部菜单栏的方法:

在res目录下新建menu文件夹,在该文件夹下新建用于菜单栏的xml文件:

举例说明菜单栏的写法,只添加一个选项元素:

xml 复制代码
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/app_info"
        android:title="@string/app_info"/>
</menu>

二、在活动代码中添加菜单栏显示

java 复制代码
@Override
public boolean onCreateOptionsMenu(Menu menu){
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

常见问题1:应用顶部菜单不显示?

修改应用主题xml文件,在parent这里去掉DayNight后面的内容:

xml 复制代码
<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="Base.Theme.WeilaYinuo" parent="Theme.Material3.DayNight">
        <!-- Customize your light theme here. -->
        <!-- <item name="colorPrimary">@color/my_light_primary</item> -->
    </style>

    <style name="Theme.WeilaYinuo" parent="Base.Theme.WeilaYinuo" />
</resources>

常见问题2:菜单跳转事件提示id必须是常量?

java 复制代码
public boolean onOptionsItemSelected(@NonNull MenuItem item){
        switch (item.getItemId()){
            case 1:
                Intent intent = new Intent();
                intent.setClass(LoginActivity.this, AppInfoActivity.class);
                startActivity(intent);
        }
        return true;
    }

switch语句的case条件必须是整数(从上到下排列),不能是菜单xml文件中定义的id。

相关推荐
zhangphil28 分钟前
Android GPU的RenderThread Texture upload上传Bitmap优化prepareToDraw
android
柿蒂2 小时前
聊聊SliverPersistentHeader优先消费滑动的设计
android·flutter
假装多好1233 小时前
android三方调试几个常用命令
android·1024程序员节·三方,gms
侧耳4293 小时前
android11禁止安装apk
android·java·1024程序员节
JohnnyDeng944 小时前
ArkTs-Android 与 ArkTS (HarmonyOS) 存储目录全面对比
android·harmonyos·arkts·1024程序员节
2501_915918415 小时前
iOS 26 查看电池容量与健康状态 多工具组合的工程实践
android·ios·小程序·https·uni-app·iphone·webview
limingade5 小时前
手机摄像头如何识别体检的色盲检查图的数字和图案(下)
android·1024程序员节·色盲检查图·手机摄像头识别色盲图案·android识别色盲检测卡·色盲色弱检测卡
文火冰糖的硅基工坊5 小时前
[嵌入式系统-150]:智能机器人(具身智能)内部的嵌入式系统以及各自的功能、硬件架构、操作系统、软件架构
android·linux·算法·ubuntu·机器人·硬件架构
2501_915909066 小时前
iOS 架构设计全解析 从MVC到MVVM与使用 开心上架 跨平台发布 免Mac
android·ios·小程序·https·uni-app·iphone·webview
明道源码7 小时前
Android Studio 创建 Android 模拟器
android·ide·android studio