【安卓开发】【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。

相关推荐
戴誉杰1 分钟前
JAVA 程序员cursor 和idea 结合编程
java·ide·intellij-idea·cursor
lincats1 小时前
# 一步一步学习使用LiveBindings(10) LiveBindings绑定到漂亮的TCombobox
ide·delphi·livebindings·delphi 12.3
沅霖2 小时前
下载Android studio
android·ide·android studio
xzkyd outpaper2 小时前
Kotlin 协程线程切换机制详解
android·开发语言·kotlin
Near_Li3 小时前
uniapp-使用mumu模拟器调试安卓APP
android·uni-app
zhangphil4 小时前
Android MediaMetadataRetriever取视频封面,Kotlin(1)
android·kotlin
斯幽柏雷科技5 小时前
[已解决]VSCode右键菜单消失恢复
ide·vscode·编辑器
Code季风6 小时前
深入理解 Gin 框架的路由机制:从基础使用到核心原理
ide·后端·macos·go·web·xcode·gin
onthewaying7 小时前
详解 Android GLSurfaceView 与 Renderer:开启你的 OpenGL ES 之旅
android·opengl
aqi008 小时前
FFmpeg开发笔记(八十)使用百变魔音AiSound实现变声特效
android·ffmpeg·音视频·直播·流媒体