我正在尝试使用自定义视图的数据绑定(George Mount 在此处显示的可能用法).
无法想象在没有<merge>标签的情况下构建复合视图.但是,在这种情况下,数据绑定失败:
MyCompoundView 类:
public class MyCompoundView extends RelativeLayout {
MyCompoundViewBinding binding;
public MyCompoundView (Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
private void init(Context context){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
binding = MyCompoundViewBinding.inflate(inflater, this, true);
}
Run Code Online (Sandbox Code Playgroud)
my_compound_view.xml:app:isGone="@{!data.isViewVisible}"我希望控制整个复合视图的可见性
<?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="data" type="com.example.MyViewModel"/>
</data>
<merge
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:isGone="@{!data.isViewVisible}">
<ImageView
android:id="@+id/image_image"
android:layout_width="60dp"
android:layout_height="60dp"
app:imageUrl="@{data.imagePhotoUrl}"/>
<!-- tons of other views-->
</merge>
</layout>
Run Code Online (Sandbox Code Playgroud)
编译器错误:
Error:(13) No resource identifier …Run Code Online (Sandbox Code Playgroud) 我无法获得带有合并根标记的布局来处理视图绑定。是否可以?
include_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="@+id/include_test"
layout="@layout/merge_layout"/>
</FrameLayout>
Run Code Online (Sandbox Code Playgroud)
合并布局.xml:
<?xml version="1.0" encoding="utf-8"?>
<merge
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/include_test">
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="A Title"/>
</merge>
Run Code Online (Sandbox Code Playgroud)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = IncludeLayoutBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.includeTest.title.text = "New Title"
}
Run Code Online (Sandbox Code Playgroud)
运行时异常:
java.lang.NullPointerException: Missing required view with ID: includeTest