每当 Kotlin 中的 arraylist 发生更改时如何更新 textview
how to update textview whenever changes happen in arraylist in Kotlin
我在 activity_main
文件中有 textview
和 arraylist
,并且我想在发生更改时更改 TextView 的文本值。
class MainActivity : AppCompatActivity(){
var list = ArrayList<Product>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
我知道如何通过单击按钮来实现,但我希望它以一种方式绑定或连接,只要数组列表中发生更改,textview 就应该立即反映更改。
谢谢
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
}
}
我在 activity_main
文件中有 textview
和 arraylist
,并且我想在发生更改时更改 TextView 的文本值。
class MainActivity : AppCompatActivity(){
var list = ArrayList<Product>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
我知道如何通过单击按钮来实现,但我希望它以一种方式绑定或连接,只要数组列表中发生更改,textview 就应该立即反映更改。
谢谢
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
}
}