小编sat*_*ssy的帖子

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

我使用 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: …
Run Code Online (Sandbox Code Playgroud)

kotlin android-studio android-studio-4.1

6
推荐指数
2
解决办法
2万
查看次数