我为单击BindingAdapter上的关闭图标写了一个自定义Chip:
@BindingAdapter("onCloseClicked")
fun Chip.onCloseClicked(onCloseClicked: () -> Unit) {
setOnCloseIconClickListener { onCloseClicked() }
}
我将其像这样绑定在我的布局中:
<?xml version="1.0" encoding="utf-8"?>
<layout>
<data>
<variable
name="viewModel"
type="com.example.playground.MyViewModel" />
</data>
<LinearLayout 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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<com.google.android.material.chip.Chip
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="chip 1"
app:closeIconEnabled="true"
app:onCloseClicked="@{() -> viewModel.chip1CloseClicked()}" />
<com.google.android.material.chip.Chip
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="chip 2"
app:closeIconEnabled="true" />
</LinearLayout>
</layout>
[当我仅绑定1个芯片时(如上),一切正常。当我也像绑定第二个芯片时:
<com.google.android.material.chip.Chip
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="chip 2"
app:closeIconEnabled="true"
app:onCloseClicked="@{() -> viewModel.chip2CloseClicked()}" />
由于数据绑定错误,该应用程序不再构建:
com / example / playground / databinding / ActivityMainBindingImpl.java错误:缺少返回语句
关于为什么会发生这种情况以及如何解决的任何想法?
PS:您可以在这里尝试自己:https://github.com/fmweigl/ChipDatabinding
// Listener Stub Implementations
// callback impls
public final kotlin.Unit _internalCallbackInvoke(int sourceId ) {
switch(sourceId) {
case 1: {
// localize variables for thread safety
// viewModel
com.example.playground.MyViewModel viewModel = mViewModel;
// viewModel != null
boolean viewModelJavaLangObjectNull = false;
viewModelJavaLangObjectNull = (viewModel) != (null);
if (viewModelJavaLangObjectNull) {
viewModel.chip1CloseClicked();
}
return null;
}
case 2: {
// localize variables for thread safety
// viewModel
com.example.playground.MyViewModel viewModel = mViewModel;
// viewModel != null
boolean viewModelJavaLangObjectNull = false;
viewModelJavaLangObjectNull = (viewModel) != (null);
if (viewModelJavaLangObjectNull) {
viewModel.chip2CloseClicked();
}
return null;
}
}
}
此处缺少带有default
语句的return
分支。为解决此问题,您可以将标有
@BindingAdapter
注释的功能的签名更改为下一个
@BindingAdapter("onCloseClicked") fun Chip.onCloseClicked(clickListener: View.OnClickListener?) { setOnCloseIconClickListener(clickListener) }
应用更改后,将成功编译项目。