【问题标题】:Why does it still say "Unresolved reference: button" even when I have button id in xml?为什么即使我在 xml 中有按钮 ID,它仍然会显示“未解析的引用:按钮”?
【发布时间】:2021-06-18 19:27:32
【问题描述】:

我有一个简单的 android 应用程序,我想点击按钮来传递其他活动。但它说

未解析的引用:按钮

即使我在 xml 中给出 id。我不知道我错在哪里。

截图:

activity_main.xml:

   <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/button"
    android:text="Click"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

ma​​in_activity:

class MainActivity : AppCompatActivity() {

companion object {
const val USER = "user"
 }

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

    val user = User( "mayk",   "qqqq", PersonalInfo("mayk", "james"))


    button.setOnClickListener{
        val intent = Intent (this, Activity2::class.java)
        intent.putExtra(USER, user)
        startActivity(intent)
    }
   }
   }

【问题讨论】:

  • 你启用了合成插件吗? (顺便说一句,它现在已被弃用,你应该去查看/数据绑定)
  • 我添加了合成插件,但现在没有变化
  • button 上按 ALT+ENTER 并选择导入

标签: android kotlin parcelable


【解决方案1】:
val button = findViewById<View>(R.id.button)

【讨论】:

    【解决方案2】:

    即使我在 xml 中有按钮 ID,为什么还要说“未解析的引用:按钮”?

    xml 布局文件中的 id 不是 Kotlin 变量。您需要先声明一个变量val button,然后才能使用它。您还需要初始化变量以引用Button 对象。一种方法是使用

    val button = findViewById<View>(R.id.button)
    

    我建议您阅读https://d.android.com 的初学者指南,以了解 Android 编程的基础知识。

    【讨论】:

      【解决方案3】:

      无需使用 findViewById()

      转到您的 Build.Gradle(模块:应用程序) 添加以下行

      apply plugin: 'kotlin-android-extensions'
      

      id 'kotlin-android-extensions'
      

      然后它会要求你同步 然后按同步 之后它会要求您仅使用 ALT+ENTER 导入它

      更新:此解决方案已弃用

      现在你必须使用视图绑定

      在模块级 build.gradle 文件中将 viewBinding 构建选项设置为 true

      android {
      ...
      buildFeatures {
          viewBinding true
          }
      }
      

      要设置绑定类的实例以供活动使用,请在活动的 onCreate() 方法中执行以下步骤:

      private lateinit var binding: ActivityMainBinding
      
      override fun onCreate(savedInstanceState: Bundle?) {
          super.onCreate(savedInstanceState)
          binding = ResultProfileBinding.inflate(layoutInflater)
          val view = binding.root
          setContentView(view)
      }
      

      您现在可以使用绑定类的实例来引用任何视图:

      binding.name.text = viewModel.name
      binding.button.setOnClickListener { viewModel.userClicked() }
      

      欲了解更多信息,您可以查看https://developer.android.com/topic/libraries/view-binding

      【讨论】:

        猜你喜欢
        • 2021-03-04
        • 2014-08-03
        • 2022-12-19
        • 2022-11-29
        • 2014-12-07
        • 1970-01-01
        • 2012-02-27
        • 2017-06-06
        相关资源
        最近更新 更多