【问题标题】:Issue with OnClickListenerOnClickListener 的问题
【发布时间】:2019-10-16 11:53:24
【问题描述】:

我在 AndroidStudio 上的移动 kotlin 应用程序中遇到了 SetOnClickListener 问题。 我用本教程创建了菜单https://www.youtube.com/watch?v=sZWMPYIkNd8

没关系!在 HAXM 模拟器上工作正常,但我无法让我的按钮交互。教程指南告诉我使用 SetOnClickListener 初始化按钮

Android Studio 不断要求我提供更多参数,编辑器显示not-enough-information-to-infer-parameter-t-with-kotlin-and-android,这让我卡住了。

我正在学习这门语言,但解决这个问题有点超出我的范围......我需要知道什么才能正确实现 OnClickListener?

YouTube 视频上的人没有在括号中添加任何额外的短语。那我该怎么办?

【问题讨论】:

  • 请发布您尝试过的代码,以便我们提供帮助
  • 没有看到您的代码就很难提供帮助
  • 欢迎来到 Stack Overflow!我们很乐意为您提供帮助,但是您问题的当前格式/内容存在一些问题,这使得我们中的一些人很难提供帮助。如果您还没有这样做,请take the tour 并阅读"How do I ask a good question?",以便我们更轻松地为您提供帮助。这也可能有帮助:How do I write a good title?
  • 我们在这里为您提供帮助,只需发布​​您的代码,以便我们为您提供帮助并告诉您错误在哪里。

标签: android kotlin mobile-application


【解决方案1】:

确保在“view.setOnClickListener”之后使用大括号 {} 而不是括号

【讨论】:

    【解决方案2】:

    您可以通过几种不同的方式实现 OnClickListener。

    对于一个简单的实现,您可以执行以下操作:

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    
        button.setOnClickListener {
            // do something when the user clicks the button
        }
    }
    

    或者你可以让你的活动像这样处理它:

    class MainActivity : AppCompatActivity(), View.OnClickListener {
    
        override fun onCreate(savedInstanceState: Bundle?) {
           super.onCreate(savedInstanceState)
    
           <yourButton>.setOnClickListener(this)
        }
    
    
        override fun onClick(v: View?) {
          when (v) {
            (<yourButton>) -> {
    
               // do something when the user clicks the button
            }
            else -> return
          }
        }
    
    }
    

    如果您想了解更多信息,这里是一个不错的来源。 https://antonioleiva.com/lambdas-kotlin-android/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多