首页 > 解决方案 > 在 Android Studio(Kotlin)中单击按钮时更改 TextView 文本

问题描述

我最近开始学习 Kotlin,在课程中,我研究了我们在 Android 中创建了一个应用程序,它在按下按钮时会更改图像,问题是我如何创建相同的应用程序但在按钮时更改 TextView 的文本按下?

以下是适用于图像的应用程序的代码。

class MainActivity : AppCompatActivity() {

    var Images = intArrayOf(R.drawable.sophh, R.drawable.soph2, R.drawable.soph3)
    var index = 0

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

    fun ChangeImage(view: View) {
        var image_view = findViewById(R.id.image_view1) as ImageView

        image_view.setImageResource(Images[index])
        index++

        if (index == Images.size) {
            index = 0
        }
    }
}

标签: androidkotlin

解决方案


您应该在其中设置文本的setOnClickListener地方添加一个:ButtonTextView

button.setOnClickListener {
    text_view.text = "Your text"
}

推荐阅读