Kotlin:尝试使用Kotlin打印多行

问题描述 投票:0回答:3

我是Kotlin / Java的初学者。我试图制作一个移动应用程序,其思想很简单:一个按钮将当前时间打印到文本表,每按一次按钮将打印新行。

我设法使按钮打印当前行,但是当我再次按下按钮时,它覆盖了先前打印的时间。

当前我的代码如下:

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()

我不知道如何使代码记住上次打印的文本,并且在网络上找不到任何解决方案。

android kotlin multiline
3个回答
0
投票

使用附加-

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())

0
投票

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

解决方案是用此行CryTable.text = formatted.toString()替换此行CryTable.text = CryTable.text + "\n" + formatted.toString()

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

希望这会有所帮助。


0
投票

请尝试在一个变量中使用旧时间,并且当您要打印新时间时,请用\ n组合新时间和旧时间,这将起作用。

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