我想在主布局中包含一个自定义xml布局,并使用自定义xml绑定一个自定义viewModel,但是它不起作用,viewModel中的值未出现在xml中。有我的代码: Main.xml:
<layout>
<data>
<import type="com.example.databindingpractise.upDownchoiceWidget.UpDownChoiceViewModel"/>
<variable
name="upDownviewModel"
type="UpDownChoiceViewModel"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="@+id/upanddown"
app:upDownviewModel="@{upDownviewModel}"
layout="@layout/up_and_down_choice_layout"/>
</LinearLayout>
up_and_down_choice_layout.xml:
<layout >
<data>
<import type="com.example.databindingpractise.upDownchoiceWidget.UpDownChoiceViewModel"/>
<variable
name="upDownviewModel"
type="UpDownChoiceViewModel"/>
</data>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/order_around_shadow">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14dp"
android:text="@{upDownviewModel.upLocation}"/>
</LinearLayout>
MainActivity.java:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
LayoutInflater layoutInflater = LayoutInflater.from(this);
UpAndDownChoiceLayoutBinding upAndDownChoiceLayoutBinding = DataBindingUtil.inflate(layoutInflater, R.layout.up_and_down_choice_layout, null, false);
UpDownChoiceViewModel upDownChoiceViewModel = new UpDownChoiceViewModel();
upAndDownChoiceLayoutBinding.setUpDownviewModel(upDownChoiceViewModel);
}
如何将upDownChoiceViewModel
与up_and_down_choice_layout.xml
绑定,有人可以解决我的问题吗?
答案 0 :(得分:0)
使用如下。
<data>
<variable
name="upDownviewModel"
type="com.example.databindingpractise.upDownchoiceWidget.UpDownChoiceViewModel" />
</data>
答案 1 :(得分:0)
您的代码应如下所示
<layout>
<data>
<variable
name="upDownviewModel"
type="com.example.databindingpractise.upDownchoiceWidget.UpDownChoiceViewModel"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="@+id/upanddown"
app:upDownviewModel="@{upDownviewModel}"
layout="@layout/up_and_down_choice_layout"/>
</LinearLayout>
up_and_down_choice_layout
<layout >
<data>
<variable
name="upDownviewModel"
type="com.example.databindingpractise.upDownchoiceWidget.UpDownChoiceViewModel"/>
</data>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/order_around_shadow">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14dp"
android:text="@{upDownviewModel.upLocation}"/>
</LinearLayout>