开发者

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

开发者 https://www.devze.com 2022-12-20 03:04 出处:网络
I am new to both Android and Stack Overflow. I have started developing and Android App and I am wondering two things:

I am new to both Android and Stack Overflow. I have started developing and Android App and I am wondering two things:

1) Is it possible to parametrize a TextView? Lets say 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}". Then at run time I would populate parameters accordingly. I haven't been able to figure out how to do this or similar approach 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, whatever. 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,开发者_如何学JAVA 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, Im looking for something similar to their mechanism to map domain objects / models to views (e.g. spring:forms).

Thanks a lot in advanced for your help. Hope this is useful for somebody else =) bye!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消