How to show integer from activity in XML?

Deadly 提交于 2019-12-23 23:15:03

问题


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 code 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?


回答1:


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.




回答2:


int app_Integer = 10;

Convert from int to String to set in your textview::

String app_String = "" +app_Integer;


来源:https://stackoverflow.com/questions/2859850/how-to-show-integer-from-activity-in-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!