首页 > 解决方案 > Android Studio 数据绑定问题

问题描述

有时,当在 XML 中使用标签时,为父布局创建的 Binding 不包含对所包含布局的 Binding 的引用。相反,包含的布局被视为一个视图。这只会影响 Android Studio(因此会自动完成),但是当您构建项目时,它会通过对包含布局的 Binding 的引用正确构建。这似乎只影响项目中的一些文件。

例如,如果布局 A 包含布局 X 和布局 Y,则它可能具有布局 X 的绑定,而布局 Y 被视为视图。在这种情况下,项目中的每个文件都将无法看到 Layout Y 的绑定。

似乎没有一种模式会导致文件受此影响。如果我手动删除缓存 ~/User/Library/Caches/Google/AndroidStudio4.1 文件夹,问题往往会出现在一组不同的文件中。

活动:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/coordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".feature.sidemenu.AboutActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <include
            android:id="@+id/toolbar"
            layout="@layout/appbar_toolbar" />

        <include
            android:id="@+id/about_layout"
            layout="@layout/fragment_about" />

    </LinearLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

工具栏:

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

    <TextView
        android:id="@+id/toolbarText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/elements_spacing"
        android:text="Toolbar"
        android:textSize="@dimen/text_size_medium" />
</layout>

关于:

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

    <TextView
        android:id="@+id/aboutText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/elements_spacing"
        android:text="About"
        android:textSize="@dimen/text_size_medium" />
</layout>

和科特林代码:

        binding.aboutLayout.apply {
            aboutText.text = "" // I get error here (when I compile everything works)
        }
        binding.toolbar.apply {
            toolbarText.text = "" // But not here
        }

Kotlin 代码

标签: androidandroid-studiodata-binding

解决方案


推荐阅读