我正在尝试将一个值传递给包含的布局,并认为@M.Pomeroy对这个问题的回答是完美的。然而,当我尝试实现它时,传递的值没有通过。这是我正在尝试的一个简化示例:
MainActivity.kt:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
activity_main.xml:
<?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"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="W00t!"
/>
<include
layout="@layout/included_layout"
android:id="@+id/the_included_layout"
app:theWord="@{`Woof!`}"
/>
<TextView
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="W00t!"
/>
</LinearLayout>
</layout>
(两个 TextView 只是为了指示所包含的布局应出现在屏幕上的位置)
included_layout.xml:
<?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"
>
<data>
<variable
name="theWord"
type="java.lang.String"
/>
</data>
<TextView
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{theWord}"
android:textSize="48sp"
android:background="#22FF0000"
/>
</layout>
(红色背景只是为了显示包含的 TextView 的位置)
这就是我应用程序的 build.gradle 文件中的内容:
android {
. . .
buildFeatures {
dataBinding = true
}
. . .
}
最后,输出如下:
如您所见,红色 TextView 中没有文本。 我也尝试过将“包含”TextView 包装在 LinearLayout 之类的东西中,但这没有帮助。
知道我错过了什么吗?
好的,已经解决了。
结果我不得不使用
setContentView(...)
而不是用DataBindingUtil.setContentView(...)
充气。
但是,简单地添加
DataBindingUtil
会导致“没有足够的信息来推断类型”错误,因此我使用的最后一行是:
DataBindingUtil.setContentView(this, R.layout.activity_main) as ViewDataBinding