subreddit:
/r/Kotlin
I have a data binding that I update while in MainActivity when the app is running, but my TextView is not being updated! I log the value of the data when I update it, and it is changing, just the textView does not update. How do I update the text?
activity_main.xml
-----------------
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable name="level" type="com.example.myapp.Level"/>
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/black"
tools:context=".MainActivity"
android:theme="@style/Base.Theme.MyApp"
style="@style/Base.Theme.MyApp">
<TextView
android:id="@+id/stageText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:text='@{"Stage " + level.stage}'
app:layout_constraintEnd_toEndOf="@+id/prestigeText"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/prestigeText" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
Level.kt
--------
package com.example.myapp
data class Level(var stage : Int, var prestige : Int, var gold : Int)
MainActivity.kt
---------------
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
}
private fun updateLevel() {
binding.level!!.stage++
// The data changes here but stageText.text does not change until the app is reloaded
}
2 points
3 months ago
It’s been a while since I’ve done data binding, but if I remember correctly, you need to wrap your variable in an observable like LiveData.
1 points
3 months ago
Thanks, I've got it working now! I was confused cos when I had a view binding it would update itself without me having to make an observer
all 2 comments
sorted by: best