繁体   English   中英

Android 导航抽屉:在 NavigationView 中垂直居中菜单

[英]Android navigation drawer: center menu vertically in NavigationView

我正在使用android.support.design库中的 NavigationView。 我想让它的菜单垂直居中。

所以,而不是默认对齐...

在此处输入图像描述

...我希望它看起来像这样:

在此处输入图像描述

据我所见, NavigationView中没有任何布局属性可以帮助我实现这一目标。 我尝试使用android:foregroundGravity="center_vertical"但没有运气。

有谁知道无需更改NvigationView以获得不同布局的方法来解决此问题?

如果不创建自定义NavigationView,这看起来是不可能的。

但是,由于NavigationView是FrameLayout的子类;因此, 您可以在其中添加自己的视图。

因此,您不能设置菜单项,而是添加自己的ListView(设置android:layout_gravity="center_vertical" )。

显然,您将需要实现一个ListAdapter,并且不能使用不理想的OnNavigationItemSelectedListener。

为时已晚,但这是为新人准备的。
您可以在NavigationActivity中创建一个RelativeLayout ,其中将包含一个android:layout_gravity="start"以便它保持定位在 window、 android:gravity="center_vertical"的左侧,从而使“导航视图”垂直居中“垂直居中” "RelativeLayout" 和app:headerLayout="@layout/nav_header_home"在执行 java 端onClickListener时更改菜单容器。

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout 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:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<include
    android:id="@+id/app_bar_home"
    layout="@layout/app_bar_home"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<RelativeLayout
    app:headerLayout="@layout/nav_header_home"
    android:layout_width="70dp"
    android:layout_height="match_parent"
    android:background="@color/bg_dark"
    android:gravity="center_vertical"
    android:layout_gravity="start">

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="70dp"
        android:layout_height="wrap_content"
        android:layout_gravity="start"
        android:background="@color/bg_dark"
        android:fitsSystemWindows="true"
        app:itemIconTint="@color/white"
        app:itemTextColor="@color/white"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:menu="@menu/activity_home_drawer" />
</RelativeLayout>
</androidx.drawerlayout.widget.DrawerLayout>

你可以在这里查看结果

当我将 app:itemHorizontalPadding="80dp" 添加到我的 activity_main.xml 文件时
它的工作和我的导航菜单项与中心对齐所以我认为这是解决这个问题的最简单的方法

我的代码:我的代码截图

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM