DEV Community

Tvisha
Tvisha

Posted on

How to switch localization resource in Android

Resources are text strings, layouts, sounds, graphics, and any other static data that your Android app needs. An app can include multiple sets of resources, each customized for a different device configuration. When a user runs the app, Android automatically selects and loads the resources that best match the device.

This topic focuses on localization and locale. For a complete description of resource-switching and all the types of configurations that you can specify (screen orientation, touchscreen type, and so on), see Providing Alternative Resources.

When you write your app, you create default and alternative resources for your app to use. When users run your app, the Android system selects which resources to load, based upon the device's locale. To create resources, you place files within specially named subdirectories of the project's res/ directory.

Why default resources are important
Whenever the app runs in a locale for which you have not provided locale-specific text, Android loads the default strings from res/values/strings.xml. If this default file is absent, or if it's missing a string that your app needs, then your app doesn't run and shows an error. The example below illustrates what can happen when the default text file is incomplete.

Example:

An app's Kotlin-based or Java-based code refers to just two strings, text_a and text_b. This app includes a localized resource file (res/values-en/strings.xml) that defines text_a and text_b in English. This app also includes a default resource file (res/values/strings.xml) that includes a definition for text_a, but not for text_b:

When this app is launched on a device with locale set to English, the app might run without a problem, because res/values-en/strings.xml contains both of the needed text strings.
However, the user sees an error message and a Force Close button when this app is launched on a device set to a language other than English. The app doesn't load.
To prevent this situation, android application developers make sure that a res/values/strings.xml file exists and that it defines every needed string. The situation applies to all types of resources, not just strings: You need to create a set of default resource files containing all the resources that your app calls upon (layouts, drawables, animations, and so on). For information about testing, see Testing for Default Resources.

Top comments (0)