David Green
David Green

Reputation: 83

how to update textview whenever changes happen in arraylist in Kotlin

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)

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.

thanks

Upvotes: 0

Views: 1888

Answers (1)

Fartab
Fartab

Reputation: 5493

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

Upvotes: 1

Related Questions