我通过数据绑定(bind)将 Interfaces
的 List
与类型参数绑定(bind)在一起。
接口(interface):
public interface MyInterface<T> {
T getValue();
}
View 模型:
public class MyViewModel {
public ObservableField<List<MyInterface>> name = new ObservableField<>();
}
绑定(bind)适配器:
@android.databinding.BindingAdapter("bind")
public static void bind(TextView textView, List<MyInterface> list) {
}
XML:
<data>
<variable
name="viewModel"
type="com.example.myname.playground4.MyViewModel"/>
</data>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:bind="@{viewModel.name}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
只要 ViewModel
在 Java 中,这就有效。
当我将 ViewModel
转换为 Kotlin 时:
class MyKotlinViewModel {
val name = ObservableField<List<MyInterface<*>>>()
}
我的 ActivityMainBindingImpl.java
出现错误:
error: incompatible types: Object cannot be converted to List
这是错误的方法:
@Override
protected void executeBindings() {
long dirtyFlags = 0;
synchronized(this) {
dirtyFlags = mDirtyFlags;
mDirtyFlags = 0;
}
android.databinding.ObservableField viewModelName = null;
java.util.List viewModelNameGet = null;
com.example.fweigl.playground4.MyKotlinViewModel viewModel = mViewModel;
if ((dirtyFlags & 0x7L) != 0) {
if (viewModel != null) {
// read viewModel.name
viewModelName = viewModel.getName();
}
updateRegistration(0, viewModelName);
if (viewModelName != null) {
// read viewModel.name.get()
viewModelNameGet = viewModelName.get(); // error is here
}
}
// batch finished
if ((dirtyFlags & 0x7L) != 0) {
// api target 1
com.example.fweigl.playground4.BindingAdapter.bind(this.mboundView0, viewModelNameGet);
}
}
有人知道这个问题的原因和/或如何解决这个问题吗?
你可以自己尝试我的测试项目@ https://github.com/fmweigl/playground4 . (工作)java 版本在分支“master”上,(非工作)kotlin 版本在分支“kotlin”上。
最佳答案
我认为您的问题与 BindingAdapter 有关。在 Kotlin 中,您必须将 @JvmStatic
注释添加到 BindingAdapter 的顶部。
像这样:
@JvmStatic
@BindingAdapter("bind")
fun bind(recyclerView: RecyclerView, items: MutableList<SmartResult>) {
//Anything that you wanna do ...
}
因为当您的 ViewModel
一个 XML
想要使用您的绑定(bind)适配器时,它必须像在 java 中一样是静态的!
关于android - 使用 Kotlin 和泛型进行数据绑定(bind)。错误 : incompatible types: Object cannot be converted to List,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53450641/