【问题标题】:Android Studio 'findViewById' no longer workingAndroid Studio 'findViewById' 不再工作
【发布时间】: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&lt;TextView&gt;(R.id.myText)
  • 您必须从android.R.id.myText 中删除android 部分并输入您自己项目的R 类。

标签: android kotlin


【解决方案1】:

android. 是问题所在!我删除了它,一切又好了。

谢谢大家!一定是一种复制粘贴错误;-))

现在我可以继续......

很棒的论坛! 非常感谢 一月

【讨论】:

    【解决方案2】:

    在 kotlin 中,您不需要设置 findViewById,而是可以像这样调用 TextView 名称:myText.setText(userNameWithMsg)

    【讨论】:

    • 只有在使用特殊库时才适用。我讲的是每本教科书所训练的标准。
    • @Janus 这不是真的,findViewById 今天没有受过现代书籍的训练,因为它很烂
    【解决方案3】:

    android.R.id.something只用于android自己的内部资源。您应该删除它,它会正常工作。

    【讨论】:

      猜你喜欢
      • 2011-10-12
      • 2022-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多