我是一名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 Output
或Event 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")
}
我必须使用
private fun myButtonPressed() {
Toast.makeText(this, "this briefly appears inside the emulator", Toast.LENGTH_SHORT).show()
}
我是在做错事还是应该以这种方式工作?
我必须添加才能使用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 ***
}