![](/img/trans.png)
[英]findViewByID in Android Studio not working with EditText
[英]Android Studio 'findViewById' no longer working
我對 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)
}
}
android.R.id.something
只用於android自己的內部資源。 你應該刪除它,它會正常工作。
在 kotlin 中,您不需要設置findViewById
而是可以像這樣調用TextView
名稱: myText.setText(userNameWithMsg)
android。 是問題所在。 我刪除了它,一切又好了。
謝謝你們; 一定是一種復制粘貼錯誤;-))
現在我可以在 go 上.....
很棒的論壇! 非常感謝簡
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.