我通过数据绑定(bind)将ListInterfaces与类型参数绑定(bind)在一起。

接口(interface):

public interface MyInterface<T> {

    T getValue();

}

ViewModel:
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出现错误:



这是错误的方法:
@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中,您必须在BindingAdapter的顶部添加@JvmStatic批注。

像这样:

@JvmStatic
@BindingAdapter("bind")
fun bind(recyclerView: RecyclerView, items: MutableList<SmartResult>) {
     //Anything that you wanna do ...
}

因为当您的ViewModelXML要使用您的绑定(bind)适配器时,它必须像Java中一样是静态的!

10-07 12:46
查看更多