Zax
Zax

Reputation: 3010

Android: Handling Internationalization/multi-language during runtime

I'm implementing internationalization for my application. The main part of the internationalization is supporting multi-languages.

One approach for supporting multi-language is, creating multiple values directories under the res/ directory and having strings.xml for the corresponding languages. Example here.

But my requirement is something like this:

The user enters his credentials to login to the application. Based on the language selected while creating an account on this app, the user would have selected a language.

So, on successful login, i'll be making a call to a service that will be returning all the strings in the application. And dynamically i must be associating these string to the labels in the application.

How can the above thing be done efficiently?

One approach that i have thought is, make a call to the service on successful login and store all the information on the Shared Preferences. and then use it.

Is there any other way to do this? How do i change the text in cases of the xml layout files having android:text=""?

Please share your views regarding the same.

Upvotes: 0

Views: 212

Answers (1)

rupps
rupps

Reputation: 9907

Take a look at Change language programmatically in Android . Whatever you do, you should use Android standard way (resources) instead of reinventing the wheel.

Update: Due to your strange constraints, if you decide to reinvent the wheel, you could for example create derived classes using the TAG field of the views, something like:

public class LocalizableTextView extends TextView {


    public LocalizableTextView(Context ctx, AttributeSet attrs) {

        super(ctx, attrs);
        setText(MyLocalizableStuff.get(this.getTag());
    }


}

and create a static helper class MyLocalizableStuff like this: (needs error checking, etc, just typed out of my head)

public static class MyLocalizableStuff {

    private static HashMap<Integer,String> sStringTable=new HashMap<>();

    public static String get(Object code) {

        Integer intCode=Integer.valueOf((String)code);
        String result=sStringTable.get(intCode);
        return result;
    }

    public static void init(Context ctx) {

        // read your strings and store them on the stringtable
        // you will call this init from onCreate like
        // MyLocalizableStuff.init(context)

    }


}

This way, you can insert LocalizableTextViews in your XML and assign a (numeric) TAG code that will map to the String and in construction time, will be assigned to the TextView. You could also use Strings as the code, but bear in mind that the HashMap will then be slower.

You could also use a SparseArray to store the string table instead of a HashMap, it will be probably faster.

But again, I wouldn't go this route.

Upvotes: 2

Related Questions