Micah
Micah

Reputation: 10395

Dynamic Android App Localization

I have read here that localization in Android apps occurs via XML files that are deployed with the app.

Is it possible to dynamically load those XML files at run-time into the app?

If not, is it possible to override the binding between the UI XML and the resources XML in such a way that I can bind to my own, dynamically loaded XML file instead of one in res/values?

Thanks

Upvotes: 12

Views: 4838

Answers (2)

Bryan Herbst
Bryan Herbst

Reputation: 67259

If you'd like, you could reinvent the wheel and implement your own Locale-based resource loading.

You can get the current Locale via

Locale = context.getResources().getConfiguration().locale;

Then use the results from that to appropriately load your own Strings/Drawables/whatever. Of course you have to do all that programmatically (XML layouts won't automatically use the correct resources).

I would highly recommend sticking with the standard localization techniques.

Upvotes: 2

CommonsWare
CommonsWare

Reputation: 1007554

Is it possible to dynamically load those xml files at runtime into the app?

No, sorry.

If not, is it possible to override the binding between the UI xml and the resources XML in such a way that I can bind to my own, dynamically loaded xml file instead of one in res/values?

Nothing in res/values/ is ever used, unless you use it. Hence, there is nothing to "override".

For example, suppose that you have a TextView. You want it to display some text. You want that text to be localized. Normally, you would set up a series of string resources, one per translation, and then use those string resources with the TextView (e.g., android:text in a layout, or setText() in Java). In your case, you would not set up string resources, but "do your own thing", and call setText() as needed.

What you lose in your approach is the automatic conversion. If the user switches languages while your app is running, Android will treat that as a configuration change and restart your activities as they return to the foreground. Normally, that would automatically load in the new string resources. In your case, it won't, because you are not using string resources. Instead, you will need to tell Android to not restart your activities (via android:configChanges) and manually reload all your TextView, etc. widgets yourself. And if you forget one, well, the user is just screwed.

IMHO, unless somebody is pointing a gun at your head to force you to try to change translations without shipping new versions of the app, just use string resources and ship new versions of the app.

Upvotes: 10

Related Questions