Android Studio添加BottomNavigationView后设计界面空白问题咨询
你的BottomNavigationView显示空白主要有两个原因:
- 没有绑定对应的菜单资源,底部导航需要菜单项才能显示内容
- 将
android:layout_height设为match_parent,导致组件占满整个屏幕,即便有菜单也无法正常显示底部导航样式
步骤1:创建底部导航菜单文件
在res/menu目录下新建bottom_nav_menu.xml文件(若没有menu目录,右键res文件夹新建Directory命名为menu即可),添加如下内容:
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/nav_home" android:icon="@drawable/ic_home" android:title="首页"/> <item android:id="@+id/nav_chats" android:icon="@drawable/ic_chats" android:title="聊天"/> <item android:id="@+id/nav_profile" android:icon="@drawable/ic_profile" android:title="我的"/> </menu>
提示:
@drawable/xxx需要替换为你项目中的图标资源,也可使用系统自带图标。
步骤2:修改activity_main.xml布局
调整BottomNavigationView的高度、绑定菜单并添加底部约束:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <com.google.android.material.bottomnavigation.BottomNavigationView android:id="@+id/bottom_nav" android:layout_width="match_parent" android:layout_height="wrap_content" app:menu="@menu/bottom_nav_menu" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent"/> </androidx.constraintlayout.widget.ConstraintLayout>
关键修改点:
- 高度改为
wrap_content,让组件自适应菜单大小 - 通过
app:menu绑定创建好的菜单文件 - 添加约束将底部导航固定在屏幕底部
步骤3:验证效果
重新编译运行项目,底部导航即可正常显示设置的菜单项。
内容的提问来源于stack exchange,提问作者ابو رئيس Abo reis
相关产品推荐
相关产品推荐

