Kotlin:尝试使用 Kotlin 打印多行

Kotlin: Trying to print multiple line with Kotlin

我是 Kotlin 初学者/Java。我试图制作一个想法很简单的移动应用程序:一个按钮将当前时间打印到文本 table 并且每次按下按钮都会打印新行。

我设法让按钮打印当前行,但是当我再次按下按钮时,它会覆盖之前打印的时间。

目前我的代码如下所示:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val CryButton = findViewById<Button>(R.id.CryButton)
    val CryTable = findViewById<TextView>(R.id.CryTable)


    CryButton.setOnClickListener {
        val current = LocalDateTime.now()
        val formatter = DateTimeFormatter.ofPattern("hh-mm")
        val formatted = current.format(formatter)

        CryTable.text = formatted.toString()

我不知道如何让代码记住最后打印的文本,而且我在网上找不到任何解决方案。

使用追加-

val CryButton = findViewById<Button>(R.id.CryButton)
val CryTable = findViewById<TextView>(R.id.CryTable)

CryTable.text = ""

CryButton.setOnClickListener {
val current = LocalDateTime.now()
val formatter = DateTimeFormatter.ofPattern("hh-mm")
val formatted = current.format(formatter)

CryTable.append(formatted.toString())

您需要更改的不是仅仅替换 TextView 的文本,而是必须向其添加新行。

解决方法是将这一行 CryTable.text = formatted.toString() 替换为这一行 CryTable.text = CryTable.text + "\n" + formatted.toString()

这将使您的文本视图保留旧文本,向其添加新行,然后添加新文本。

希望对您有所帮助。

请尝试将旧时间放入一个变量中,当您打印新时间时,使用 \n 将新时间与旧时间连接起来,它会起作用。