Android Studio 中有些事情尚未完成,因为您尚未实际实现数据绑定。
将变量添加到布局后data
元素,即inflate
方法将如您所愿找到。也就是说,您实际上并没有通过直接通过绑定设置文本字段的值来获得数据绑定的好处。您应该在绑定中设置视图模型,然后让绑定相应地更新视图。例如:
创建视图模型:
public class MyViewModel {
public final ObservableField<String> name;
public MyViewModel(String name) {
this.name = new ObservableField<>(name);
}
}
并在您的布局中使用它
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="model" type="com.victoriaschocolates.conceirge.MyViewModel" />
</data>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{model.name}"
android:padding="10dp"
android:background="#000"
android:textColor="#fff"
android:layout_gravity="center"
/>
</FrameLayout>
</layout>
(注意variable
声明于data
元素,以及如何在 TextView 中引用它text
属性)
然后在您的自定义视图中绑定两者:
public class MyCustomView extends FrameLayout {
public MyCustomView(Context context) {
this(context, null, 0);
}
public MyCustomView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
MyCustomBinding binding = MyCustomBinding.inflate(inflater, this, true);
MyViewModel model = new MyViewModel("Whatever");
binding.setModel(model);
}
}
当然,最好还是通过自定义视图类中的 setter 传入数据,甚至从容器视图中传入数据(请参阅http://developer.android.com/tools/data-binding/guide.html#includes http://developer.android.com/tools/data-binding/guide.html#includes)