I'm just wondering what the benefits/overheads are for using @string
rather than hard coding strings within the actual Java code... For Example:
// To get the string resource:
getActivity.setTitle(getString(R.string.my_string));
Is this the best practice for Things like Actionbar titles, Dynamically created button text, ect... Or should I just do this:
// Hardcoded string
getActivity.setTitle("My String");
I know there will be a bit more overhead doing it the first way.. Just not sure what best practice is.
You should add them to a string resource file and then reference them from your layout. This allows you to update every occurrence of the word "Yellow" in all layouts at the same time by just editing your strings. xml file. It is also extremely useful for supporting multiple languages as a separate strings.
In computer programming or text markup, to hardcode (less frequently, hard code ) is to use an explicit rather than a symbolic name for something that is likely to change at a later time. Such coding is sometimes known as hardcode (noun) and it is more difficult to change if it later becomes necessary.
Hardcoded string are the literal strings. So, What you may be referring to is, literal strings in the data. C# Copy Code.
Open the Settings / Preferences dialog Ctrl+Alt+S , expand Editor and click Inspections. Select the desired profile, and locate the node Internationalization under Java. Enable the Hardcoded strings inspection to highlight hard-coded string literals in the editor. Apply changes and close the dialog.
Incase you were unaware as to the actual point of having the @string
system please read over the localization documentation. It allows you to easily locate text in your app and later have it translated.
Edit Thanks to Hippo for clearing this up.
Using multiple strings of the same value no matter the method (Strings.xml vs programatically) doesn't seem to have any associated overhead. According to Oracle "All literal strings and string-valued constant expressions are interned" which means that the object is reused rather than re-created if you use it again.
That way you have a fixed place to alter all your strings within the project. Lets say you used same string in 10 different locations in the code. What if you decide to alter it? Instead of searching for where all it has been used in the project you just change it once and changes are reflected everywhere in the project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With