I use XML output in my app. So basically the main activity just tells the android to show the XML layout of main.
But what if I have in the activity cod开发者_如何学编程e defined integer variable and I want this integer variable also be shown on the display?
How do I PUSH the integer variable to the XML??? From main XML reference to other strings in XML is easy - @string/app_name ... but how do I use the integer variable from the activity?
Presumably you're showing some text in a TextView
.
You can display text either from a string resource (defined in XML and referred to as R.string.*
, as you mention) or from a String
at runtime.
You can't change the XML resources at runtime; you use them for fixed values like labels or other UI text. So there's no way to "push" a value to XML.
But you can happily do something like this at runtime, dynamically updating your UI:
int userAge = calculateUsersAge();
TextView age = (TextView) findViewById(R.id.age_field);
age.setText(userAge +" years old");
Or better, ensuring there are no hardcoded values in the code:
age.setText(getString(R.string.years_old, userAge));
Where years_old
is the text "%d years old" in your res/values/strings.xml
and "%d Jahre alt" in your res/values-de/strings.xml
, and so on.
int app_Integer = 10;
Convert from int to String to set in your textview::
String app_String = "" +app_Integer;
精彩评论