How to find how many language's string.xml present in my application

225 Views Asked by At

I need to find how many language's string.xml is present in my application at run time. Example: I have string.xml for en, zh,fr.. and now my server is sending me language type as hi then I should check whether hi present in values folder or not???

Thanks in advance.

1

There are 1 best solutions below

0
On

Since your strings could be in a file other than string.xml, here's a more robust way to do this:

Take a string id that you know is translated into all your supported languages and test if it's different than the default.

    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    Configuration configuration = new Configuration(getResources().getConfiguration());

    configuration.locale = new Locale(""); // default locale
    Resources resources = new Resources(getAssets(), metrics, configuration);
    String defaultStr = resources.getString(R.string.hello); // default string

    // lang is the two-character language code, e.g. "zh", "hi"

    configuration.locale = new Locale(lang);
    resources = new Resources(getAssets(), metrics, configuration);
    String testStr = resources.getString(R.string.hello);
    boolean supported = !defaultStr.equals(testStr);
    Log.d(TAG, lang + " is " + (supported ? "" : "not ") + "supported");

Note that Configuration.locale is deprecated since Nougat. See the docs for update.