【发布时间】:2015-08-05 07:37:02
【问题描述】:
尝试在我的项目中使用新的 Android 数据绑定,但在尝试将“android:tag”属性设置为某个自定义变量时出现错误。
我的 menu_item.xml 文件:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="menuItem"
type="com.example.MenuItem" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:tag="@{menuItem}"
tools:ignore="UseCompoundDrawables">
<!--suppress AndroidUnknownAttribute -->
<ImageView
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:imageResource="@{menuItem.itemType.drawableId}" />
<TextView
android:id="@+id/displayName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{menuItem.itemType.displayNameId}" />
</LinearLayout>
</layout>
我的 MenuItem 类:
public class MenuItem {
public final ItemType itemType;
public MenuItem(ItemType itemType) {
this.itemType = itemType;
}
}
部分生成的MenyItemBinding.java:
public MenuItemBinding(View root) {
super(root, 0);
final Object[] bindings = mapBindings(root, 3, sIncludes, sViewsWithIds);
this.displayName = (android.widget.TextView) bindings[2];
this.displayName.setTag(null);
this.icon = (android.widget.ImageView) bindings[1];
this.icon.setTag(null);
this.mboundView0 = (android.widget.LinearLayout) bindings[0];
this.mboundView0.setTag(root.getResources().getString(com.myApp.R.string.@{menuItem}));
setRootTag(root);
invalidateAll();
}
错误出现在生成的类中,尝试设置绑定视图的Tag。
任何想法如何解决这个问题?最好不要使用自定义的 LinearLayout 来支持这一点。
【问题讨论】:
-
你能打印 LogCat 吗?我从来没有直接在 xml 中设置标签,甚至不知道这是可能的。但是在这里,如果您尝试将 MenuItem 设置为标签,我猜 Android 会抱怨,因为它找不到 MenuItem 的空构造函数。
-
这是一个编译时错误。请参阅上面生成的类的一部分。更具体地说,错误出现在 'this.mboundView0.setTag(root.getResources().getString(com.myApp.R.string.@{menuItem}));' .关于空的构造函数 - 我也将 menuItem 用于 TextView 和 ImageView 并且没有任何抱怨。
标签: android data-binding