即使方向发生变化,我也可以本地化Android应用程序吗?

时间:2015-12-09 07:16:14

标签: android

我有一个过流菜单,从中点击语言以获得singlechoiceitems(语言列表)。我写了这段代码

AlertDialog.Builder languageDialog = new AlertDialog.Builder(
                    MainActivity.this);
            languageDialog.setTitle(R.string.chooseLanguage);
            final String[] languageOptions = { "English", "Nepali" };
            languageDialog.setSingleChoiceItems(languageOptions, 0,
                    new DialogInterface.OnClickListener() {
                        @SuppressLint("NewApi")
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (which == 0) {
                                setLanguage("es");
                            } else if (which == 1) {
                                setLanguage("ne");
                            }
                            dialog.dismiss();
                        }
                    });
            languageDialog.show();
for list of Dailog and 
@SuppressLint("NewApi")
private void setLanguage(String language) {
    Locale locale = new Locale(language);
    Locale.setDefault(locale);
    android.content.res.Configuration config = new Configuration();
    config.locale = locale;
    this.getResources().updateConfiguration(config,
            this.getResources().getDisplayMetrics());
    MainActivity.this.recreate();
} method to set locale 

问题是在屏幕方向上更改语言会更改回设备语言,为什么?我缺少什么? 我在阅读时已对anroid清单文件进行了更改,但没有解决方案适用于我。有什么帮助吗?

4 个答案:

答案 0 :(得分:1)

在特定活动的 AnroidMenifest.xml 文件中添加以下行。

android:configChanges="orientation|layoutDirection|screenSize"

答案 1 :(得分:0)

是的,遗憾的是,改变语言不是Android喜欢的。要使其工作,您需要在onCreate之前在EACH活动中调用setLanguage方法。

答案 2 :(得分:0)

changing orientation destroy activity and **recreate** it so when it **recreated** it changes to language that set in **oncreate** method.you have to save value in **saveinstatestate** and check on **oncreate** method

if(saveinstatntate!=null)`enter code here`
{
//then set the saved language
}
else
{
//defaultvalue
}

答案 3 :(得分:0)

我想,您应该添加Android Manifest文件:

android:configChanges="locale|orientation"

在你班上你应该有这些进口:

import java.util.Locale; 
import android.os.Bundle; 
import android.app.Activity; 
import android.content.Intent; 
import android.content.res.Configuration; 
import android.content.res.Resources; 
import android.util.DisplayMetrics; 

,本地化代码应如下所示:

public void setLocale(String lang) 
{ 
myLocale = new Locale(lang); 
Resources res = getResources(); 
DisplayMetrics dm = res.getDisplayMetrics(); 
Configuration conf = res.getConfiguration(); 
conf.locale = myLocale; 
res.updateConfiguration(conf, dm); 
Intent refresh = new Intent(this, AndroidLocalize.class); 
startActivity(refresh); 
finish();
} 

请阅读:How to change language of app when user selects language?

另请阅读:

Change language programmatically in Android

Set-up the application Language in Android Preferences