首页 > 解决方案 > Android数据绑定错误:在布局文件中导入与java.lang.Error同名的类时出现编译错误

问题描述

在我的代码中,我创建了一个具有成功、错误和加载状态的密封资源类,如下所示:

package com.sample.githubsample.vo

sealed class Resource<T>(val data: T?, val message: String? = null)

class Success<T>(data: T?) : Resource<T>(data)

class Error<T>(data: T?, message: String?) : Resource<T>(data, message)

class Loading<T>(data: T?) : Resource<T>(data)

我正在尝试在我的 xml 布局中使用 Resource 类来操作视图的可见性。以下是我的布局文件(trending_fragment.xml):

<layout 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">

    <data>

        <import type="android.view.View" />
        <import type="com.sample.githubsample.vo.Success" />
        <import type="com.sample.githubsample.vo.Loading" />
        <import type="com.sample.githubsample.vo.Error" />

    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
            android:id="@+id/pull_to_refresh"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent">

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/repo_list"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
                app:layout_constraintTop_toTopOf="parent" />
        </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

但是我收到以下错误:

e: [kapt] An exception occurred: android.databinding.tool.util.LoggedErrorException: Found data   `  `binding error(s):`
[databinding] {"msg":"Error has already been defined as java.lang.Error but trying to re-define as 
com.sample.githubsample.vo.Error","file":"D:\\KotlinProjects\\GithubSample\\app\\src\\main
\\res\\layout\\trending_fragment.xml","pos":[]}

at android.databinding.tool.processing.Scope.assertNoError(Scope.java:111)
at android.databinding.annotationprocessor.ProcessDataBinding.doProcess(ProcessDataBinding.java:124)
at android.databinding.annotationprocessor.ProcessDataBinding.process(ProcessDataBinding.java:88)
at org.jetbrains.kotlin.kapt3.base.incremental.IncrementalProcessor.process(incrementalProcessors.kt)
at org.jetbrains.kotlin.kapt3.base.ProcessorWrapper.process(annotationProcessing.kt:147)

如果我将我的 Error 类重命名为与 Java 默认类不冲突的其他名称,那么它可以正常工作。

我尝试在数据绑定中使用类型别名,但仍然遇到相同的错误。使用数据绑定时在布局中使用类名有什么限制吗?

标签: androidkotlinandroid-databindingandroid-architecture-components

解决方案


推荐阅读