Kotlin -运行 按下按钮时打印语句
Kotlin -Run print statement when button is pressed
我是一名 Swift
开发人员,我刚刚进入 Kotlin
,所以我不熟悉它的工作原理。
在 Swift
中,如果我创建一个按钮并向其添加一个 action/target,并且在该操作中我添加一个 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 ***
}
我是一名 Swift
开发人员,我刚刚进入 Kotlin
,所以我不熟悉它的工作原理。
在 Swift
中,如果我创建一个按钮并向其添加一个 action/target,并且在该操作中我添加一个 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 ***
}