【问题标题】:Kotlin Error at runtime - Unresolved reference Object ID运行时的 Kotlin 错误 - 未解析的引用对象 ID
【发布时间】:2021-04-07 09:00:48
【问题描述】:

我开始学习使用 Kotlin 进行 Android 开发。我试图在 MainActivity.kt 中调用对象 ID,但出现错误 Unresolved reference : btnDatePicker

下面是代码

<Button
    android:id="@+id/btnDatePicker"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="15dp"
    android:background="#0E0B0B"
    android:text="SELECT DATE"
    android:textColor="#C5BBBB"
    android:textSize="20sp"
    android:textStyle="bold"
    app:backgroundTint="#186C64" />

下面是 MainActivity.kt 中的代码

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    btnDatePicker.setOnClickListener { Toast.makeText(this, "works", Toast.LENGTH_LONG).show() }


    }
}

将鼠标悬停在 btnDatePicker 上时,我看到以下选项,但不确定如何继续

【问题讨论】:

  • 它没有定义,你应该通过 findViewById、kotlin 合成、jetpack 视图绑定来获取参考...清理并重建您的项目
  • 这能回答你的问题吗? Unresolved reference: kotlinx

标签: android kotlin


【解决方案1】:

看起来您正在尝试使用合成视图绑定。您的项目需要在 build.gradle 中启用 kotlin-android-extension 插件,例如:

apply plugin: 'kotlin-android-extensions'

之后您应该可以导入您的btnDatePicker

请注意,不推荐使用 kotlin-android-extensions 和合成视图绑定,因此使用 Jetpack 视图绑定可能会更好。见https://developer.android.com/topic/libraries/view-binding/migration

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多