【问题标题】:simpler way of setting onClickListener for a button in Kotlin在 Kotlin 中为按钮设置 onClickListener 的更简单方法
【发布时间】:2021-03-05 19:14:41
【问题描述】:

我有一个简单的按钮,我想为其设置一个 onclicklistener,我首先通过findViewById 尝试了两种方法,效果很好,但是我们可以通过 if 直接从 kotlin 代码访问button

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="232dp"
    android:text="Button"
    app:layout_constraintBottom_toTopOf="@+id/textView"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

Kotlin 代码

这种方法效果很好

val btnClickMe = findViewById<Button>(R.id.button) 
btnClickMe.setOnClickListener {
   // do something
}

当我尝试通过 kotlin 代码中的 id 直接访问按钮时,它不起作用

 button.setOnClickListener {
           //do something
        }

错误:未解析的引用按钮

我在尝试一些不可能的事情吗?如果没有关于如何解决此问题的任何建议,请

谢谢 回复

【问题讨论】:

    标签: android kotlin


    【解决方案1】:

    当我尝试通过 kotlin 代码中的 id 直接访问按钮时,它不起作用

    有可能吗?

    是的,但是……

    通过能够直接引用组件而不使用 findViewById,您尝试实现的目标称为合成导入,它允许您执行此操作。问题是这些现在已弃用,您应该使用 viewBinding 或仅使用标准 findViewById


    相关信息:

    https://developer.android.com/topic/libraries/view-binding/migration

    Unresolved reference - activity does not recognize synthetic imports in android studio v4

    【讨论】:

      【解决方案2】:

      Kotlin 合成允许直接通过 id 访问视图的组件,但它已被弃用。 android documentation

      现在您应该使用视图绑定。

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

      【讨论】:

      • 领先你几秒钟 :) 但是是的
      • 下次我会努力更快的,呵呵:)
      猜你喜欢
      • 2019-11-07
      • 1970-01-01
      • 1970-01-01
      • 2018-10-28
      • 2014-05-18
      • 1970-01-01
      • 1970-01-01
      • 2021-10-04
      • 2017-01-09
      相关资源
      最近更新 更多