【问题标题】:how to update textview whenever changes happen in arraylist in Kotlin每当Kotlin中的arraylist发生更改时如何更新textview
【发布时间】:2023-03-13 23:58:01
【问题描述】:

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

class MainActivity : AppCompatActivity(){

var list = ArrayList<Product>()


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

我知道如何通过单击按钮来做到这一点,但我希望它以某种方式绑定或连接,只要 arraylist 中发生更改,textview 应该立即反映更改。

谢谢

【问题讨论】:

  • 使用安卓 LiveData。如果您需要示例,请告诉我。
  • 是的,请举个例子,谢谢@Fartab

标签: android kotlin arraylist textview


【解决方案1】:

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

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 
    }
}

【讨论】:

    猜你喜欢
    • 2020-06-10
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 2020-11-23
    相关资源
    最近更新 更多