If we are creating an Android application we need to write text on it. Labels, application information, fields, hints... lots of text and sentences are needed. How can we deal with this? We can do it in two ways: The wrong way and the Android way.
The wrong way is just putting the text “statically", in the element we need. For example, in an xml TextView attribute:
android:Text="Text Without using string.xml"
or in a TextView object in Android code:
textViewObject.setText(“Text without using string.xml")
Well, we can think that this way of inserting text is not bad at all, but let's analyze it a bit deeper.
Imagine that the person you are working with/for doesn't like the text you have written, and wants to change all of it. Now, you have to check, line by line, file by file, in xml and in .java files all the text you have inserted and replace all of it. Interesting work, eh?... if we were monkeys, but we are programmers, so let's do it in a right way.
Android gives us a very useful way to use text and sentences in our application. This is implemented by using the string.xml file inside the Resources folder. Here, all the strings are stored so they can be retrieved in the application. What happens if the boss-person want us to change all texts? Just go to this file and replace them. More easy, quick and effectively.
Let's see how this string.xml file is composed.
<?xml version="1.0" encoding="utf-8"?>
<string name="sentence2">This is a Sentence</string>
For every String we want to put in our application, just add a line. In the “name" attribute, put the identifier of the string, something easy to remember and easily organizable, at the beginning of the application, maybe you have 10 or 20 strings...but if the app grows, you can easily have thousands of strings...so it's important that you have the criteria to put in the name. Inside the <string> tags, just put the string you want to use.
Now...how do you use this from the application?
We can use the strings we have created in the string.xml file, from two different places: From a layout defined in xml or from the Android code. Let's go a bit further.