Search code examples
androidxmlmvvmdata-bindingtextview

Android: How to display multiple values in one and the same TextView using dataBinding?


Hi all: I have 1 TextView and 4 different clickable Buttons that fetch the data that I'm trying to display in that TextView.

So, every time a button is pressed data should be fetched and displayed. The problem is that when I use dataBinding I pretty much "hardcode" the data that I get from the "call" in the xml like this:

android:text="@{viewModel.triviaAnswer}"

So, what about other values from the ViewModel? How to display them in the same TextView?

I tried xml ternary statements and such but it did not help much, for now...

In other words, the idea is to press button 1, fetch data, display it. Press button 2, fetch data and display in the same textView. And so on...I want to reuse that TextView somehow.

How would you approach this problem. I guess the simplest thing, would be to just have a different textView for each onClick call and hide/show them when needed.

Can you think of anything that would be helpful in this case?

Thanks a lot.


Solution

  • The best way to do it is to reuse your viewModel.triviaAnswer as well. Let's say its a String then assign the value to that String. For example if I click Button 1 the String value of viewModel.triviaAnswer will become "One", for Button 2 viewModel.triviaAnswer will become "Two" and so on...