Android 工作室在使用具有数据绑定的自定义视图时不会生成布局预览


class SimpleView @JvmOverloads constructor( context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {
init {
val inflater = LayoutInflater.from(context)
SimpleViewBinding.inflate(inflater, this, true)
}
fun setObjData(uiState: UiState<ExampleData>) {
if (uiState is UiState.Data) {
binding.obj = uiState.data
}
}
}

对应布局:simple_view.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"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="obj"
type="com.project.example.model.dataObject" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/abcid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="@{obj.title}"
android:textColor="@color/black"
android:textSize="@dimen/text_size_20sp"
app:layout_constraintTop_toTopOf="parent"
tools:text="Test" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>

其他布局中的用法如下,但此其他布局(使用simpleView的地方(不会生成预览。

<androidx.appcompat.widget.LinearLayoutCompat
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<com.project.example.view.SimpleView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:ObjData="{@viewmodel.obj}"/>

注意:只有在simple_view.xml 中未使用数据绑定android:text="@{obj.text}"时才生成预览

Preview似乎在Chipmunk | 2021.2.1上运行良好,而在新的Dolphin和更高版本上,它不起作用。

https://developer.android.com/studio/archive

最新更新