It's not really an error, it's a warning (Warning):
Severity: Warning ...
He is telling you that it is not a good practice to put handwritten strings in your layouts (XML files).
The best practice is to use the string resources to declare your strings there.
In the project path you have this file: res/values/strings.xml
in which Android recommends that you declare your strings.
It looks like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="appName">Mi Aplicación</string>
<string name="otraCadena">Cualquier cosa</string>
</resources>
If you then want to use any string in an element of a layout, let's say a TextView:
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/otraCadena" />
And if you want to use otraCadena
in 200 parts of your App, you would do it in the same way:
... android:text="@string/otraCadena" />
How useful is that?
Suppose it turns out that there is an error in otraCadena
or there is a change in estaOtraCadena
, you only change the value once in strings.xml
and it is updated everywhere. Or do you prefer to look for it and change it 200 times?
That's why Android warns you that it's not a good idea what you're trying to do.
Also, the same error message tells you some reasons why this practice is not recommended:
- When creating configuration variations (for example, for landscape or portrait), you must repeat the actual text (and keep it updated when making changes)
- The application can not be translated into other languages simply by adding new translations for existing string resources. There are quick fixes to automatically extract this encoded string in a resource search.
With other elements, not just strings
This practice is recommended not only with the chains, but with other elements such as colors, styles, dimensions, images ... in short, everything in the res/values/...
folder of any Android project.
If you open the colors.xml
file by the example, you will see something like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
</resources>
You can use those resources combined with styles.xml
to apply styles and colors to the layout elements:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
If you want to change the color of any element, just change its value in colors.xml
, without having to worry about looking in the code or in the layouts, every time that color appears.
As you can see, the res
folder is very interesting and saves you a lot of work.