我用 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
有人可以告诉我错误或我的错误的原因吗?
代码如下。
构建等级:
android {
...
// <-- added
buildFeatures {
viewBinding = true
}
// -->
}
资源/布局/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>
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)
}
}