Kotlin-Android First App Unresolved Reference TextView Button 等

Kotlin-Android First App Unresolved Reference TextView Button etc

我是 Android 和 Kotlin 开发的新手。

我想从一个简单的 "Hello World" 开始,但我已经 运行 遇到了问题。

我向我的 MainActivity 添加了一个 Textview,并想设置一个 onClick 侦听器来更改我拖入 activity 的 TextView 的文本。

编译器现在抱怨 'TextView' 是一个未解析的引用(它对 Buttons 等也是如此)。

然后我按照网站的建议添加了一个 kotlinx 导入,但这并没有解决任何问题。下面的代码示例,任何带有星号作为行注释的内容都是我添加的。

package com.example.my.mynewapp

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.fragmentX.view.* // *

class MainActivity : AppCompatActivity() {

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

        val textView: TextView = findViewById(R.id.testView) as TextView  // *
        textView.setOnClickListener { // *
            textView.text = "You clicked me! You flipping clicked me!" // *
        } // *

    }
}

有人知道发生了什么事吗?

您正在 class 中充气 activity_main.xml
这个TextView是否属于上面的布局?
如果是,那么您不需要 findViewById()
只需添加到您的导入:

import kotlinx.android.synthetic.main.activity_main.*

不是

import kotlinx.android.synthetic.main.fragmentX.view.*

然后在 activity class.

中的任何位置使用 testView(这是 TextView 的 ID,除非它是错字)

应该是自动导入的,但是应该有

import android.widget.<WhateverIsMissing>

用未解析的引用替换 WhateverIsMissing

  • 项目文件夹下有gradle个脚本
  • 打开build.gradle(模块:您的应用名称)
  • 将 'id-android-extensions' 添加到插件中
  • 然后同步它

还有一件事要检查您的导入是否完整:

如果您为 activity、片段等定义了多个布局,请确保相应控件的 类 跨布局匹配。这是我看到此错误消息的最常见情况。

添加应用插件:'kotlin-android-extensions'在build.gradle 通过双移搜索并编写“构建”,然后在 dependencies 部分添加插件,然后应该会为您显示导入选项

如果您使用 Android Studio v.4.2.1,您必须像这样在 (build.gradle) 文件中添加此行:-

id 'kotlin-android-extensions'

添加新视图时(在本例中为 TextView),IDE 会将其 id 默认为 textView每次添加相同类型的新视图时,IDE 将递增 idtextView2textView3,等等on) 即使您已经删除了以前的视图。对于 example:

// Capture the layout's TextView and set the string as its text
val textView = findViewById<TextView>(R.id.textView).apply {
    text = message
}

如果从R.id.textView得到Unresolved reference: textView,检查相应的XML文件。具体来说,组件树:

要更改 id、select 视图并在 属性 window 中更改 id: