【发布时间】:2021-03-18 01:38:25
【问题描述】:
我对 Android/Kotlin 很陌生。我已经创建了一些程序并且正在取得良好的进展。 但是从今天开始,我遇到的问题是即使在标准的“Hello World”程序(空活动)中也无法运行“findViewById”。
我只在 XML 中添加了 android:id="@+id/myText" 行。
在 MainActivity.kt 中的 var myTxt = findViewById(android.R.id.myText) 行。
但我收到错误消息 Unresolved reference: 'myText' 文本“myText”是红色的。
通常的尝试:清除缓存,新项目,...我已经尝试过了。行为总是相同的。 在旧项目中,“findViewById”工作正常。但我发现工作项目和非工作项目之间的导入或设置没有区别。
Android Studio 4.1.1 中的所有内容
感谢您的帮助 一月
<?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/myText"
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.myhelloworld
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var myTxt = findViewById<TextView>(android.R.id.myText)
}
}
【问题讨论】:
-
对我来说它仍然有效。也许是别的原因
-
移除“安卓”。
var myTxt = findViewById<TextView>(R.id.myText) -
您必须从
android.R.id.myText中删除android部分并输入您自己项目的R 类。