Search code examples
javaandroidxmltextview

Is it possible to show a variable from java editing a XML activity?


I have a TextView which I would like to show how the time passes in a game (it depends on the steps followed, not on real time elapsed).

<TextView
    android:id="@+id/time_tv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Time"/> //Editing this line

Is there a way that I could set it to show variables from java to string, instead of setting a constant value?


Solution

  • This can be achieved by data binding concept in Android. A view model has to be created and associated with the text view as below.

    <TextView android:text="@{viewmodel.userName}" />
    

    Below link in android developer website explains in detail on how to create a view model. https://developer.android.com/topic/libraries/architecture/viewmodel?gclid=Cj0KCQiAuP-OBhDqARIsAD4XHpdBptAbmhtZUFWh0EpQhpvNui7pc9_Br-w8xbimKZHpBkC1K9VC6u8aAg-ZEALw_wcB&gclsrc=aw.ds