How can I add a custom item to a NavigationView with a menu layout?
The actionLayout
attribute is now supported in Android Support Library 23.1:
NavigationView provides a convenient way to build a navigation drawer, including the ability to creating menu items using a menu XML file. We’ve expanded the functionality possible with the ability to set custom views for items via app:actionLayout or using MenuItemCompat.setActionView().
So the code in the question should just work now.
NavigationView
is a subclass of FrameLayout
, which can have multiple children:
You can, however, add multiple children to a FrameLayout and control their position within the FrameLayout by assigning gravity to each child, using the android:layout_gravity attribute.
That means you can add a custom view to your NavigationView
:
<android.support.design.widget.NavigationView
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="@menu/side_menu">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_gravity="bottom">
<android.support.v7.widget.SwitchCompat
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="night_mode"/>
</LinearLayout>
</android.support.design.widget.NavigationView>
create a layout with switchcompat and mention it in menu item as
<item android:id="@+id/notification"
android:title="Notification"
app:actionLayout="@layout/notify" />`
then notify layout add this
<android.support.v7.widget.SwitchCompat
android:id="@+id/switch_compat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:checked="false"
android:onClick="notify"/>
onclick is the keyPoint,implement handler in your Activity,then it will work.
I had the same problem and found that NavigationView
behaves differently depending on:
- Whether you set the
android:title
andandroid:icon
attributes onitem
or not - What kind of view your action layout contains (e.g.
TextView
or others)
Not setting the attributes worked for completely customizing the item:
<?xml version="1.0" encoding="utf-8"?>
<menu 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"
tools:showIn="navigation_view">
<item
android:id="@+id/nav_custom"
android:title="@null"
app:actionLayout="@layout/nav_drawer_switch" />
</menu>
(Note that you can also just not set android:title
, but that results in a warning in Android Studio.)
The result:
(This is with version 27.1.1 of com.android.support:design
, not sure about other versions.)