How to set ellipsize in menu item of NavigationView?

Viewed 2929

I want set android:ellipsize="end" in menu items of NavigationView. In my current implementaion when text in menu item is too long, it's just cut at the end. Here is what I've tried so far:

<android.support.design.widget.NavigationView
        app:itemTextAppearance="@style/AppTheme.Widget.NavigationView.TextAppearance"
        android:id="@+id/navigation"
        style="@style/AppTheme.Widget.NavigationView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:menu="@menu/drawer_view"/>

<style name="AppTheme.Widget.NavigationView" parent="Widget.Design.NavigationView">
        <item name="android:textAppearance">@style/AppTheme.Widget.NavigationView.TextAppearance</item>
        <item name="android:background">@color/drawer_background</item>
        <item name="itemTextColor">@color/color_drawer_item</item>
        <item name="itemIconTint">@color/color_drawer_item</item>
</style>

<style name="AppTheme.Widget.NavigationView.TextAppearance">
        <item name="android:ellipsize">end</item>
        <item name="android:maxLines">1</item>
</style>

Edit:

Another possible solution is described here: Android NavigationView : not show full item and not truncate

2 Answers

There are 2 parts to this questions - ellipsize long names and maxLines for very long names. As mentioned in another answer, ellipsize is straightforward. Create a style:

 <style name="NavigationMenuItemTextAppearance">
    <item name="android:ellipsize">end</item>
</style>

Add this style to your NavigationView:

 <android.support.design.widget.NavigationView
    android:id="@+id/navigation_view"
    android:layout_height="match_parent"
    android:layout_width="wrap_content"
    android:layout_gravity="start"
    app:headerLayout="@layout/nav_drawer_header"
    app:menu="@menu/menu_nav_drawer"
    app:itemTextColor="@color/textColorPrimary"
    app:theme="@style/NavigationMenuItemTextAppearance">
</android.support.design.widget.NavigationView>

To set the number of lines you'd allow the name to show for, it can be done by over-riding the layout file: design_navigation_menu_item.xml. Although as per Material design guidelines, only 1 line is allowed for very long menu option material design navigation drawer

Just copy the support library's into your own design_navigation_menu_item.xml and place in the layout folder. Change maxLines="2"

 <CheckedTextView
    android:id="@+id/design_menu_item_text"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:drawablePadding="@dimen/design_navigation_icon_padding"
    android:gravity="center_vertical|start"
    android:maxLines="2"
    android:textAppearance="@style/TextAppearance.AppCompat.Body2"/>
Related