代码之家  ›  专栏  ›  技术社区  ›  fweigl

使用kotlin和泛型进行数据绑定。错误:不兼容类型:无法将对象转换为列表

  •  1
  • fweigl  · 技术社区  · 7 年前

    我绑定一个 List 属于 Interfaces 通过数据绑定使用类型参数。

    接口:

    public interface MyInterface<T> {
    
        T getValue();
    
    }
    

    ViewModel:

    public class MyViewModel {
    
        public ObservableField<List<MyInterface>> name = new ObservableField<>();
    
    }
    

    绑定适配器:

    @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编写的。

    当我转换 视图模型 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版本是在分支“主”、“(非工作)”科特林版本上的分支“KOTLIN”。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Ehsan    7 年前

    我认为你的问题在于你的bindingAdapter。 @JvmStatic BindingAdapter顶部的批注。

    这样地:

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

    因为当你 ViewModel XML 想要使用绑定适配器,它必须像Java一样是静态的!