Using layout_width & wrap_content With NavigationView

Nathan Sokalski 4,116 Reputation points
2021-10-07T16:39:16.213+00:00

I have a com.google.android.material.navigation.NavigationView with several menu items & a header for which I want it to horizontally stretch to fit. In most controls, I would simple use
android:layout_width="wrap_content"
However, this seems to have no effect with NavigationView. The only workaround I could find is to set a fixed width, which seems very inefficient. Is there a reason wrap_content is not working with NavigationView?

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,294 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. JarvanZhang 23,936 Reputation points
    2021-10-08T05:46:39.567+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    a header for which I want it to horizontally stretch to fit

    To make the header fit the the navigationView. Please set the android:layout_width of the header layout to android:layout_width match_parent instead. Here is the sample code, you could refer to it.

       <com.google.android.material.navigation.NavigationView  
           android:id="@+id/nav_view"  
           ...  
           app:headerLayout="@layout/nav_header_main"  
           app:menu="@menu/activity_main_drawer"/>  
    

    layout/nav_header_main.xml

       <?xml version="1.0" encoding="utf-8"?>  
       <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
           xmlns:app="http://schemas.android.com/apk/res-auto"  
           android:layout_width="match_parent"  
           android:layout_height="@dimen/nav_header_height"  
           ...>  
           ...  
       </LinearLayout>  
    

    Best Regards,

    Jarvan Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.