How to Move Strings into Android Resources - dummies

How to Move Strings into Android Resources

By Michael Burton

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:

  1. Create a new string resource.

  2. Copy its name.

  3. 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:

  1. In Android Studio, open a random layout file such as activity_main.xml in the layouts directory.

  2. Add a new TextView element that looks like the following:

        android:text="I need a kombucha refill, please"/>
  3. Place your cursor on the boldface line with the hardcoded text string and press Alt+Enter.

    A menu opens with various options.

  4. Choose the Extract String Resource option.

    The Extract String Resource dialog box opens, and you can set various options for the resource.


  5. 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.