How to easily extract strings from your Android code into the strings.xml file

This handy little feature can save a lot of time and manual work when working with Android apps.

If you during Android development in Eclipse use hardcoded strings in your java code, like in the example below:

package test.layout;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;

public class LayoutTest extends Activity {

	private Button btn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btn = (Button) findViewById(R.id.Button01);
        btn.setText("New Button Text");
    }
}

Maybe you want to gather them in the strings.xml file where they belong, to separate hardcoded strings from the code and to get an overview of your string resources.
This also makes it easier to internationalize your application later on.

You can just select the string to extract out, “New Button Text” on line 17, and then in the Eclipse main menu, go to

Refactor -> Android -> Extract Android String…

You can then give your new string a name, edit the string text if you want, and select where to place it (the default is in you strings.xml file: /res/values/strings.xml).

Then hit the OK button to extract your string.

Tip: You could also use the keyboard shortcut: First press Shift + Alt + A, then press S

You will notice that the hardcoded string “New Button Text” gets replaced with a resource id, R.string.new_text.

        btn.setText(R.string.new_text);

This resource makes it easy to refer to your string several places in your code, while keeping only one version of the text itself in the strings.xml file, which now looks like this:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="new_text">New Button Text</string>
</resources>

If you need to edit your text, just edit it in the strings.xml file.

Please share this tip.

  • Ant

    hi, I’ve done this a few times and now have a lot of strings and indeed a lot of resource ID’s I’d like to refactor/rename so it’s easier to figure out where they’re used…is there any way in eclipse to succesfully rename a string name or resource id ? If I refactor/rename from within the source file it only attempts to refactor R.java (doesn’t go on to change the xml file it’s defined in). I guess I could global search and replace…

  • Jesús Jiménez

    Sadly, this incredibly useful feature doesn’t support localization (multiple strings.xml), so you end up with inconsistent strings files…

  • Pingback: How to extract strings into strings.xml resource files in Android Studio | EnvyAndroid()