Why and How to use String Resources
In post Intro to Android Studio, I had a textview with “Hello World” but I didn’t really show you how to add it so let’s add the textview with text “Hello World” using drag and drop.
As you can see it’s as simple as drag and drop and then just type your text and press enter. Now on to our topic…
What is a String resource?
Strings or static text can be stored in Android in a separate resource file called strings.xml.
You can find strings.xml file inside res folder under values as shown below. I’m using project mode for my app.
Why store strings in strings.xml instead of just hard-coding it?
The reason is if you hard code your static strings like we did in the gif above and then in the future you want to translate your app in multiple languages you will have to go in find and change every single string in the app. You won’t be able to just send a text file and have someone translate it for you.
To avoid that problem, it’s a good practice to start using string resources from the start. Remember that this is not required but rather just a good practice.
How to extract and store a string in strings.xml?
- Open the xml file of your activity and change to Text Mode
- Move the cursor to text and press ALT+Enter.
- Select Extract String resource
- Give your resource a name and click ok.
Here’s the gif of the entire process of extracting a string to strings.xml in android studio.
There you have it. Your string is now stored in strings.xml file as a resource. Your xml file will update to reflect the change.
Let me know any comments or concerns.