每当 Kotlin 中的数组列表发生变化时如何更新文本视图 [英] how to update textview whenever changes happen in arraylist in Kotlin

查看:31
本文介绍了每当 Kotlin 中的数组列表发生变化时如何更新文本视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 activity_main 文件中有 textviewarraylist 并且我想在发生更改时更改 TextView 的文本值.

I have textview and arraylist in activity_main file and and I want to change the text value of TextView whenever a change happens.

class MainActivity : AppCompatActivity(){

var list = ArrayList<Product>()


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

我知道如何通过单击按钮来完成它,但我希望它以一种方式绑定或连接,每当 arraylist 中发生更改时,textview 应立即反映更改.

I know how to do it with button click but i want it to be binded or connected in a way that whenever changes happen there in arraylist the textview should reflect the changes immadiately.

谢谢

推荐答案

LiveData 开始用于需要根据可观察状态自动更新视图的情况.

LiveData came to be used in situations when your view needs to automatically be updated based on an observable state.

class MainActivity : AppCompatActivity(){

    // this live data holds the state of your view
    val productsLiveData = MutableLiveData<List<Product>>()

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

        // initialize state with an empty list
        productsLiveData.value = ArrayList()

        // register an observer to be notified on every state change.
        productsLiveData.observe(this, Observer{
            //here you should bind state to view
            myTextView.text = it.joinToString(", ")
        })
    }

    fun updateList(product: Product){
        val oldProducts = productsLiveData.value
        val newProducts = oldProducts + product
        // update live data value, so observers will automatically be notified
        productsLiveData.value = newProducts 
    }
}

这篇关于每当 Kotlin 中的数组列表发生变化时如何更新文本视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆