get the application's resources languages

后端 未结 11 1120
庸人自扰
庸人自扰 2020-12-02 23:30

Is it possible, at runtime, to know which resources languages are embedded in my app?

i.e the presence of this folders:

values-en
values-de
values-fr         


        
11条回答
  •  旧时难觅i
    2020-12-03 00:09

    Inspired by the answers above I created a simple method to get all app's languages based on provided translations:

    public static Set getAppLanguages( Context ctx, int id ) {
      DisplayMetrics dm = ctx.getResources().getDisplayMetrics();
      Configuration conf = ctx.getResources().getConfiguration();
      Locale originalLocale = conf.locale;
      conf.locale = Locale.ENGLISH;
      final String reference = new Resources( ctx.getAssets(), dm, conf ).getString( id );
    
      Set result = new HashSet<>();
      result.add( Locale.ENGLISH.getLanguage() );
    
      for( String loc : ctx.getAssets().getLocales() ){
        if( loc.isEmpty() ) continue;
        Locale l = Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT_WATCH ? new Locale( loc.substring( 0, 2 ) ) : Locale.forLanguageTag( loc );
        conf.locale = l;
        if( !reference.equals( new Resources( ctx.getAssets(), dm, conf ).getString( id ) ) ) result.add( l.getLanguage() );
      }
      conf.locale = originalLocale;
      return result; 
    }
    

    where as id arg should be used a R.string.some_message which is provided in all translations and contains clearly distinguishable text, like "Do you really want to delete the object?"

    Maybe it would help someone...

提交回复
热议问题