我正在尝试使用数据绑定库基于用户角色设置不同的菜单。
在下面的代码片段中,如果用户是教育工作者,那么我会设置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
最后
George Mount的回答是正确的,我只是添加了BindingAdapter
。
@BindingAdapter("app:menu")
public static void setMenu(NavigationView navigationView, int id) {
navigationView.inflateMenu(id);
}
<layout>
标签包装您的NavigationView。 - D.J"
和'
-app:menu ='@ {viewModel.getModel.getRole.equals("educator")?@ menu / activity_main_educator_drawer:@ menu / activity_main_child_drawer}'
- yennsarah"
,'
和```组合,但都不起作用。 - Samuele Colombo