如何通过数据绑定使用自定义视图膨胀线性布局

How inflate a Linear layout with custom view by databinding

我只想用一些 Vertical LinearLayout 制作一个地图,每个地图都有一个 Horizo​​ntal LinearLayout 并且在每个地图中布局想要膨胀一个类似于下面代码的视图:

each_cell.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:android="http://schemas.android.com/apk/res/android">
<data>
    <variable name="live" type="Integer" />
    <variable name="i" type="Integer" />
    <variable name="j" type="Integer" />
</data>

<ImageView
    android:id="@+id/itemView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="30sp"
    app:setI="@{i}"
    app:setJ="@{j}"/>

each_row.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/row_instance"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="2dp"
    android:orientation="horizontal">

</LinearLayout>

我会将这个水平 LL 视图添加到我的主垂直 LL 并且将创建地图

和科特林代码:

            val cell = DataBindingUtil.inflate<EachCellBinding>(inflater , R.layout.each_cell , HorizontalLinearLayout.row_instance , true   )

但错误是:

Required DataBindingComponent is null in class EachCellBindingImpl. A BindingAdapter in com.example.gameoflife.SartFragment.StartFragment is not static and requires an object to use, retrieved from the DataBindingComponent. If you don't use an inflation method taking a DataBindingComponent, use DataBindingUtil.setDefaultComponent or make all BindingAdapter methods static.

如错误所示,您已在 com.example.gameoflife.SartFragment.StartFragment 中声明了绑定适配器方法。在 class 中声明它使其成为非静态的。但是绑定适配器方法应该始终是静态的。因此,从 class 内部获取方法并将其放在 class 外部,它将变为静态,您的错误将得到解决。