Samuele Colombo Samuele Colombo - 9 months ago 48
Android Question

Android Data Binding conditional menu?

I'm try to set different menus based on the user's role using the data binding library.

In the fragment of code below you can see that if the user is an educator I would set the

activity_main_educator_drawer
otherwise the
activity_main_child_drawer
.

<?xml version="1.0" encoding="utf-8"?>
<layout
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"
xmlns:bind="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="user"
type="sc.me.twelve.viewmodels.UserViewModel" />
</data>
<android.support.v4.widget.DrawerLayout
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@{user.getModel.getRole.equals(`educator`) ? @menu/activity_main_educator_drawer : @menu/activity_main_child_drawer}" >

<include
layout="@layout/nav_header_main"
bind:user="@{user}" />

</android.support.design.widget.NavigationView>

</android.support.v4.widget.DrawerLayout>
</layout>


It seems good, but I have this error:

****/ data binding error ****msg:Identifiers must have user defined types from the XML file. activity_main_educator_drawer is missing it


 
 

FINALLY



The George Mount's answer is the right one, I've just added the
BindingAdapter
.

@BindingAdapter("app:menu")
public static void setMenu(NavigationView navigationView, int id) {
navigationView.inflateMenu(id);
}

Answer Source

It looks like the menu resource isn't being recognized. Try this expression instead:

    <android.support.design.widget.NavigationView
        ...
        app:menu="@{user.getModel.getRole.equals(`educator`) ? R.menu.activity_main_educator_drawer : R.menu.activity_main_child_drawer}" >

Make sure to import the R class:

<data>
    <import type="sc.me.twelve.R"/>
</data>

or whatever your package is.

I see a small strangeness in your expression. I think it can be simplified:

app:menu="@{user.model.role.equals(`educator`) ? R.menu.activity_main_educator_drawer : R.menu.activity_main_child_drawer}"

The "get" or "is" prefix is assumed for accessor methods.