viewBinding 无法正常工作并出现错误(Android studio 4)

sat*_*ssy 6 kotlin android-studio android-studio-4.1

我使用 Android studio 4 (4.11) 使用 kotlin 制作 Android 应用程序。

findViewById 在 Androd Studio 4 中已弃用,然后我使用 viewBinding。 https://developer.android.com/topic/libraries/view-binding

但 viewBinding 无法正常工作,出现错误。

(path)/MainActivity.kt: (6, 31): Unresolved reference: ActivityMainBinding
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我错误的原因或我的错误吗?

代码如下。

构建.等级:

  android {
  ...
// <-- added
    buildFeatures {
        viewBinding = true
    }
// -->
  }
Run Code Online (Sandbox Code Playgroud)

资源/布局/activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/viewText" // added.
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
Run Code Online (Sandbox Code Playgroud)
package com.example.myapplication

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

private lateinit var binding: ActivityMainBinding // added. <== error (6:31)

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

// <-- added.
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        binding.textView.text = "Test view binding."
// -->

        setContentView(R.layout.activity_main)
    }
}
Run Code Online (Sandbox Code Playgroud)

Kew*_*ewi 12

在启用视图绑定的情况下构建项目时,我还收到数据绑定错误。这个问题和一些答案可能对任何遇到Arctic Fox + Java 11问题的人有用。升级后,我将应用程序 build.gradle 条目中的编译选项更改为:

    sourceCompatibility JavaVersion.VERSION_11 
    targetCompatibility JavaVersion.VERSION_11
//Required if using new Java 11 language features in your project
Run Code Online (Sandbox Code Playgroud)

我收到错误:未找到包 (*.databinding),并认为未生成视图绑定。在尝试了多种补救措施并找到生成的绑定后,我遇到了上述问题。由于我没有在项目中使用任何新的语言功能,因此我将 build.gradle 中的编译选项更改回:

compileOptions {
     sourceCompatibility JavaVersion.VERSION_1_8
     targetCompatibility JavaVersion.VERSION_1_8
}
Run Code Online (Sandbox Code Playgroud)

重建项目,绑定全部恢复,没有编译错误。

根据teralser 的回答,“此问题已修复并已在 BB canary 8 中解决。它特定于 Java 11”。

对于运行 Android 4.0(API 级别 14)或更高版本以及 Android Gradle Plugin 3.0.0+ 的设备,按照链接添加 Java 8 编译选项可能会解决您的问题。


小智 9

其中之一可能有帮助

  • 重建项目(构建->重建项目)
  • 文件 -> 使 Chaches 无效 -> 无效并重新启动