简体   繁体   中英

Use string from MainActivity.java in activity_main.xml

I have a string defined in MainActivity.java:

public String counter1 = String.valueOf(e.getCount());

I would like to use this string in activity_main.xml as:

android:text="@string/counter1"

As you can tell I am very new to this so basic steps would be appreciated.

Thanks

Short answer: you cannot. The resources you set in your xml layouts must be statically defined in resources files, like.-

<string name="counter1">COUNTER VALUE</string>

To dynamically define new strings, you must set them programmatically.-

TextView textView = (TextView) findViewById(R.id.textViewId);
textView.setText(counter1);

What do you want to do if you could get this to work? If you want to set text dynamically, you can use setText :

yourTextView.setText(counter1);

If you want to set something programmatically which you can... you should use

txtview.setText(yourString);

if you want to set a String in XML then you either set it in the XML like you did

  android:text="Exercise Name"

or using strings which then you can use programmatically as well in strings:

   <string name="Delete">Delete</string>

in code you can call it with R.string.Delete or getString(R.string.app_name);

of course you can also set from strings in XML with @string...

by the sound of what you are trying to do, you want the TextView to change while program is running so the first option would suit you well

you can not,if you want to acheive this kind of solution: create string in strings.xml

<string name="counter1">value of counter</string>

and if you want to set the text of counter dynamically then in you activity:

TextView tView = (TextView) findViewById(R.id.textViewId);
tView.setText(counter1);

you should follow this,because all static strings shoul always be defined in strings.xml

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM