Santiago
Santiago

Reputation: 1585

Android TextViews. Is parametrization possible? Is binding to model possible?

I started developing an Android App and I am wondering:

  1. Is it possible to parametrize a TextView? I want to render a text message which states something like: "The user age is 38". Lets suppose that the user age is the result of an algorithm. Using some typical i18n framework I would write in my i18n file something like "The user age is {0}". At run time I would populate parameters accordingly. I haven't figured out how to do this or similar in Android.

  2. Let's suppose I have a complex object with many fields. Eg: PersonModel which has id, name, age, country, favorite video game, etc. If I want to render all this information into a single layout in one of my activities the only way I have found is getting all needed TextViews by id and then populate them one by one through code. I was wondering if there is some mapping / binding mechanism in which I can execute something like: render(myPerson, myView) and that automatically through reflection each of the model properties get mapped into each of the TextViews. If someone has ever worked with SpringMVC, I'm looking for something similar to their mechanism to map domain objects / models to views (e.g. spring:forms).

Upvotes: 3

Views: 192

Answers (1)

Jeremy Logan
Jeremy Logan

Reputation: 47514

In answer to #1: You want String.format(). It'll let you do something like:

int age = 38;
String ageMessage = "The user age is %d";
myTextView.setText(String.format(ageMessage, age));

The two you'll use the most are %d for numbers and %s for strings. It uses printf format if you know it, if you don't there's a quicky tutorial in the Formatter docs.

For #2 I think you're doing it the best way there is (grab view hooks and fill them in manually). If you come across anything else I'd love to see it.

Upvotes: 2

Related Questions