Kotlin-按下按钮时运行打印语句

问题描述 投票:1回答:1

我是一名Swift开发人员,我刚刚加入Kotlin,所以我不熟悉事情的运作方式。

Swift中,如果我创建一个按钮并向其中添加一个动作/目标,然后在该动作中我添加一个print statement,则会在控制台中将其打印出来。

lazy var myButton: UIButton = {
    let button = UIButton(type: .system)
    // create button
    button.addTarget(self, action: #selector(myButtonPressed), for: .touchUpInside)
    return button
}()

@objc func myButtonPressed() {
    print("this gets printed to the console")
}

但是在Kotlin中,当我有print statement时,什么都不会打印到Build OutputEvent Log

val myButton: Button = findViewById(R.id.myButtonId)
myButton.setOnClickListener { myButtonPressed() }

private fun myButtonPressed() {
    print("nothing gets printed to the console, I have to use the Toast function")
}

enter image description here

我必须使用

private fun myButtonPressed() {
    Toast.makeText(this, "this briefly appears inside the emulator", Toast.LENGTH_SHORT).show()
}

我是在做错事还是应该以这种方式工作?

ios swift kotlin printf android-button
1个回答
1
投票

我必须添加才能使用Log.d(),并且必须在Debug mode中运行它:

import android.util.Log // *** 1. include this import statement ***

private val TAG = "MainActivity" // *** 2. add this constant, name it TAG and set the value to the name of the Activity ***

val myButton: Button = findViewById(R.id.myButtonId)
myButton.setOnClickListener { myButtonPressed() }

private fun myButtonPressed() {

    Log.d(TAG, ">>>>> now this prints to the console <<<<<<") // *** 3. add the TAG inside the first param inside the Log.d statement ***
}

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.