How to Move Strings into Android Resources
As you become an experienced programmer of Android apps, you may start to take shortcuts to get your project built and working. Say that initially you forget to move strings into resources, and you have to come back at a later time to do it. You can extract a string into a resource using the built-in tools.
The long way
Here’s one way to extract a string into a resource:
Create a new string resource.
Copy its name.
Replace the string value in your layout with the resource identifier.
This way is fine. It’s not a huge pain, but it does take a little time.
The fast way
You can cut the time to create a string resource to fewer than 15 seconds. If you do this 30 times a day (which is feasible in an 8-hour day), you can save 15 minutes of just copying and pasting. That’s five hours a month doing the copy-and-paste dance!
Follow these steps:
In Android Studio, open a random layout file such as activity_main.xml in the layouts directory.
Add a new TextView element that looks like the following:
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="I need a kombucha refill, please"/>
Place your cursor on the boldface line with the hardcoded text string and press Alt+Enter.
A menu opens with various options.
Choose the Extract String Resource option.
The Extract String Resource dialog box opens, and you can set various options for the resource.
Choose a name for your resource such as kombucha_refill, leave the other options set to their defaults, and click OK.
You can now see that the layout file has been modified. The text “I need a kombucha refill, please” has been replaced with “@string/kombucha_refill”.
If you open the strings.xml file in the res/values folder, you can see your new string resource.
That’s pretty cool! You can see that doing this 20 or 30 times a day can add up and save you a lot of time.