Level Up - Android Dev: How To Automatically Extract Hardcoded Strings To res/values/strings.xml

This is just one of the many refactoring features of Eclipse. Using this extract feature, you won't even need to open res/values/strings.xml to add the String resources nor manually write out reference to the resource.

This saves a lot of time, and allows the best practice of putting String constants away from the UI/Java files so that localization can be performed easier. This method I'm about to show you is especially productive because it can change all instances of that particular String to point to the xml string resource so that you don't have to do it individually one-by-one. (I'm doing maintenance on code that has everything hardcoded, so this is a lifesaver.)

To automatically extract the String, it's easy enough:

Step 1: Highlight the entire String that you would like extracted and sent to res/values*/strings.xml
Step 2: From the menu bar, select Refactor->Android->"Extract Android String..."
Step 3: Preview options and confirm changes.

Step 2: Automatically extracting string menu option.

Step 3: Many different great refactoring options to choose from.

This works in the XML and Java files for your Android application. And, this is much quicker than manually changing all instances of hardcoded Strings to getString() and @string/.

~ Danial Goodwin ~

Post a Comment