You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Android/XML实现导航菜单移至ActionBar下方顶部位置

解决方案:将底部导航移至ActionBar下方的顶部位置

嗨,很高兴能帮到你!作为Android新手,调整导航栏位置其实只需要修改布局约束就能实现,下面是简洁完整的步骤:

1. 修改Main Activity布局XML

我们需要调整BottomNavigationView的约束条件,把它从屏幕底部移到顶部(ActionBar下方),同时更新Fragment的布局约束来适配新的导航位置。

替换你的Main Activity布局代码为以下内容:

<?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"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- 移动到顶部的导航栏,marginTop与ActionBar高度对齐 -->
    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="?android:attr/windowBackground"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="?attr/actionBarSize"
        app:menu="@menu/bottom_nav_menu" />

    <!-- Fragment区域适配导航栏位置,现在从导航栏底部延伸到屏幕底部 -->
    <fragment
        android:id="@+id/nav_host_fragment_activity_main"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/nav_view"
        app:navGraph="@navigation/mobile_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>

修改说明:

  • 移除了原来布局根容器的android:paddingTop="?attr/actionBarSize",改为给导航栏设置android:layout_marginTop="?attr/actionBarSize",确保导航栏刚好在ActionBar下方
  • 将导航栏的app:layout_constraintBottom_toBottomOf="parent"替换为app:layout_constraintTop_toTopOf="parent",固定到屏幕顶部
  • 更新Fragment的约束:app:layout_constraintTop_toBottomOf="@id/nav_view"(从导航栏底部开始)和app:layout_constraintBottom_toBottomOf="parent"(延伸到屏幕底部)

2. 可选:调整导航栏样式(按需修改)

如果顶部导航栏需要更贴合的样式,可以在BottomNavigationView中添加这些属性:

  • app:itemIconTint="@color/your_icon_color":修改图标颜色
  • app:itemTextColor="@color/your_text_color":修改文字颜色
  • android:background="@color/your_background_color":修改背景色

3. 小提示:修复导航文件的小问题

在你的mobile_navigation.xml中,toolsFragment的类名大小写可能有误(应该是首字母大写的ToolsFragment),建议修正为:

<fragment
    android:id="@+id/navigation_tools"
    android:name="com.example.gsm.ui.tools.ToolsFragment"
    android:label="@string/title_Tools"
    tools:layout="@layout/fragment_home" />

这样修改后,运行应用就能看到导航栏出现在ActionBar下方的顶部位置啦!

内容的提问来源于stack exchange,提问作者Amin Kadkhodaee

火山引擎 最新活动