'Android NavigationRail Show multiple label lines for item text
Solution 1:[1]
As per the Navigation rail - Material Design documentation it seems that there is no an official way to set multiple lines for an item text. But you can achieve this with a simple workaround like in the below example:
1.Define the NavigationRailView
in xml like the below:
<com.google.android.material.navigationrail.NavigationRailView
android:id="@+id/navigation_rail"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:labelVisibilityMode="labeled"
app:menu="@menu/navigation_rail_menu"/>
where @menu/navigation_rail_menu
contains the below sample menu items:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/menu_item_all_files"
android:enabled="true"
android:icon="@android:drawable/ic_menu_gallery"
android:title="All\nFiles" />
<item
android:id="@+id/menu_item_recent"
android:enabled="true"
android:icon="@android:drawable/ic_menu_slideshow"
android:title="Recent\nFiles" />
<item
android:id="@+id/menu_item_all_pictures"
android:enabled="true"
android:icon="@android:drawable/ic_menu_gallery"
android:title="All\nPictures" />
</menu>
2.And for each item change the Max number of lines in a programmatically way like in the below example:
//get the NavigationRailView
NavigationRailView navigationRailView = findViewById(R.id.navigation_rail);
//menu item 1
NavigationBarItemView item1 = navigationRailView.findViewById(R.id.menu_item_all_files);
BaselineLayout item1BaselineLayout = item1.findViewById(R.id.navigation_bar_item_labels_group);
setItemMaxLines(item1BaselineLayout, 2);
//menu item 2
NavigationBarItemView item2 = navigationRailView.findViewById(R.id.menu_item_recent);
BaselineLayout item2BaselineLayout = item2.findViewById(R.id.navigation_bar_item_labels_group);
setItemMaxLines(item2BaselineLayout, 2);
//menu item 3
NavigationBarItemView item3 = navigationRailView.findViewById(R.id.menu_item_all_pictures);
BaselineLayout item3BaselineLayout = item3.findViewById(R.id.navigation_bar_item_labels_group);
setItemMaxLines(item3BaselineLayout, 2);
where setItemMaxLines()
is a helper function to change for each Item the MaxLines
:
private void setItemMaxLines(BaselineLayout baselineLayout, int maxLines){
if(baselineLayout!=null){
for(int i=0; i<baselineLayout.getChildCount(); i++){
View child = baselineLayout.getChildAt(i);
if(child instanceof MaterialTextView){
((MaterialTextView)child).setMaxLines(maxLines);
((MaterialTextView)child).setGravity(Gravity.CENTER);
}
}
}
}
Result:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | MariosP |