0

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.

2
  • 1
    take a livedata of string in viewmodel and set it to textview . Update the value of the livedata and the textview data will refresh autumatically Commented Apr 17, 2020 at 17:35
  • Thank you, this made sense! Clear and concise! Commented Apr 17, 2020 at 18:06

2 Answers 2

1

A simpliest and best approach to get your buttons change one ViewModel variable viewModel.triviaAnswer thats all

Sign up to request clarification or add additional context in comments.

1 Comment

Appreciate the help!
0

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

1 Comment

Thanks a lot. Even though both comments above stated the same and made sense, the penny dropped once I read yours. Basically, we just update one viewModel variable bind it in the xml and the LiveData takes care of the rest. Thank you once again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.