Image as background in menu item
As said in the question.
What I currently have:
Desired output:
On each column there would be a background image. I’m going to remove the text and just fill items with images. Is this possible? If yes, do I need different resolutions for background images?
Activity_main_drawer.xml:
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:showIn="navigation_view"> <group android:checkableBehavior="single"> <item android:id="@+id/nav_ITEM1" android:title="@string/ITEM1" /> <item android:id="@+id/nav_ITEM2" android:title="@string/ITEM2" /> <item android:id="@+id/nav_ITEM3" android:title="@string/ITEM3" /> </group> </menu>
Depending on what exactly you are looking to do, you could try add an icon:
<item android:id="@+id/nav_ITEM1" android:icon="@drawable/item1_image" android:title="@string/ITEM1" />
EDIT / UPDATE: to set the ‘background image’ of a menu entry, try:
<com.google.android.material.navigation.NavigationView android:id="@+id/nav_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" android:fitsSystemWindows="true" app:itemBackground="@drawable/YOUR_DRAWABLE_HERE". <<<<<<<<< app:headerLayout="@layout/nav_header_home" app:menu="@menu/activity_home_drawer" />
Unfortunately, this sets the same image for each entry – but, it is a good starting point. Will update if I see a way of customising each entry.
LAST UPDATE, This allows you to define a unique background for each entry. Its not perfect, but maybe you can tweak it to work:
-
include ‘app’ in your xml for your menu:
xmlns:app="http://schemas.android.com/apk/res-auto"
-
Then, make a simple layout file that has an image:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/announce"/> </FrameLayout>
-
In menu, update the item to point to the layout file you made above
<item android:id="@+id/nav_gallery" android:title="" app:actionLayout="@layout/test" /> <<<<< HERE
Source: found some methods and ideas here: https://stablekernel.com/article/using-custom-views-as-menu-items/