首页 > 解决方案 > Android 数据绑定:在生成的数据绑定文件中找不到 ...BindingImpl

问题描述

我正在尝试使用示例项目 android-sunflower 对视图模型进行数据绑定。当前的问题是,当我尝试构建项目时,我error: cannot find symbol symbol: class FragmentShopBindingImpl location: package {{packageName}}.databinding在类中遇到错误,DataBindinMapperImpl 我不确定我在这里缺少什么,因为我添加了示例项目中的所有内容。该类FragmentShopBindingImpl没有生成,还是不应该生成?由于我在 android sunflower 示例中看不到任何以“Impl”结尾的类
我的代码:

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        val factory = InjectorUtils.provideShopViewModelFactory(context!!)
        val shopViewModel = ViewModelProviders.of(this, factory)
            .get(ShopViewModel::class.java)

        val binding = DataBindingUtil.inflate<FragmentShopBinding>(
            inflater, R.layout.fragment_shop, container, false).apply {
            viewModel = shopViewModel
            lifecycleOwner = this@ShopFragment
        }

        return binding.root
    }

布局:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable
            name="viewModel"
            type="{{packageName}}.viewmodel.ShopViewModel" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".fragments.ShopFragment">

        <TextView
            android:text="@{viewModel}"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>
</layout>

生成文件的图像(忽略 {{packageName}}:

在此处输入图像描述

标签: androidkotlindata-bindingandroid-databindingandroid-jetpack

解决方案


在 textView 标记内的 xml 代码中,对于 android:text 属性,您使用了 @{viewmodel}。它只是引用您的 shopViewModel 类,您必须针对该类中的文本变量。然后是一代。类文件错误将消失。

bindingImpl 错误主要是针对 XML-text 或 XML-onClick 属性的无效分配而生成的。


推荐阅读