Android 数据绑定条件菜单?

Android Data Binding conditional menu?

我尝试使用数据绑定库根据用户的角色设置不同的菜单。

在下面的代码片段中,您可以看到,如果用户是 教育工作者,我将设置 activity_main_educator_drawer,否则 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>

看起来不错,但是我有这个错误:

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

终于

是正确的,我刚刚添加了 BindingAdapter

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

菜单资源似乎无法识别。试试这个表达式:

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

确保导入 R class:

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

或者你的包裹是什么。

我看到你的表情有点奇怪。我认为可以简化:

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

访问器方法假定 "get" 或 "is" 前缀。