2017-04-20 44 views
3

我们可以通过将字符串文件保存在适当的值文件夹中来更改语言,如下图所示。在整个Android应用程序中更改语言

enter image description here

如何翻译这我从Web服务获取数据?有没有任何图书馆可以实现这一目标?

+1

你可以使用谷歌翻译API,但它不是免费的。 –

+1

您应该将某种标志从您的应用传递到Web服务,以告诉他们您将使用您的应用使用哪种语言,并使它们以指定语言返回数据 –

回答

3

您不能转换采用了android由Web服务返回的数据,但提到下面可以改变语言休息的应用程序:调用changeLocale方法之后

尝试重新创建活动。

changeLocale("ar"); 

private void changeLocale(String lang) { 
    updateConfiguration(activity, lang); //lang = "en" OR "ar" etc 

    activity.recreate(); 
} 

public static void updateConfiguration(Activity activity, String language) { 
    Locale locale = new Locale(language); 
    Locale.setDefault(locale); 

    Configuration configuration = new Configuration(); 
    configuration.locale = locale; 

    Resources resources = activity.getBaseContext().getResources(); 
    resources.updateConfiguration(configuration, resources.getDisplayMetrics()); 
} 
+0

这不会更改我从Web服务接收的语言?我对吗? –

+0

你的意思是来自webservices的数据? Offcourses,由Web服务返回的数据需要由服务器进行翻译。 – Pehlaj

+0

我们怎样才能从android结束呢? –

2

对于Web服务响应的翻译可以使用i18Next

I18Next i18next = I18Next.getInstance(); 
Loader loader = i18next.loader(); 
loader.load(); 
loader.lang(String lang); 
2

作为Configuration.locale =区域设置在API> = 21以下的代码可用于弃用。

public void setLocale(Context context,String lang){ 
    Locale[] locales = Locale.getAvailableLocales(); 
    // print locales 
    boolean is_supported=false; 
    //check if the intended locale is supported by device or not.. 
    for (int i = 0; i < locales.length; i++) { 
     if(lang.equals(locales[i].toString())) 
     { 
      is_supported=true; 
      break; 
     } 
     Log.e("Languages",i+" :"+ locales[i]); 
    } 
if(is_supported) { 
     Locale myLocale = new Locale(lang); 
     Resources res = context.getResources(); 
     DisplayMetrics dm = res.getDisplayMetrics(); 
     Configuration conf = res.getConfiguration(); 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 
      conf.setLocale(myLocale); 
     } else { 
      conf.locale = myLocale; 
     } 
     res.updateConfiguration(conf, dm); 
    }else{ 
     //do something like set english as default 
    } 

现在通过调用在代码中使用此功能:

setLocale("hi"); 

您需要通过调用

重新创建()刷新你的活动屏幕;

在您的活动。

相关问题