在Android中以编程方式更改应用程序语言

是否有可能在使用Android资源的同时以编程方式改变应用程序的语言?

如果不是,是否可以用特定的语言请求资源?

我想让用户改变应用程序的语言从应用程序。

490272 次浏览

这是有可能的。您可以设置区域。然而,我不建议这样做。我们在早期阶段尝试过,基本上是在对抗这个系统。

我们对改变语言有同样的要求,但决定接受UI应该与手机UI相同的事实。它是通过设置locale工作,但太bug了。根据我的经验,每次输入活动(每个活动)时都必须设置它。这里是一个代码,如果你仍然需要这个(再次强调,我不推荐)

Resources res = context.getResources();
// Change locale settings in the app.
DisplayMetrics dm = res.getDisplayMetrics();
android.content.res.Configuration conf = res.getConfiguration();
conf.setLocale(new Locale(language_code.toLowerCase())); // API 17+ only.
// Use conf.locale = new Locale(...) if targeting lower versions
res.updateConfiguration(conf, dm);

如果您有特定于语言的内容-您可以根据设置更改它。


2020年3月26日更新

    public static void setLocale(Activity activity, String languageCode) {
Locale locale = new Locale(languageCode);
Locale.setDefault(locale);
Resources resources = activity.getResources();
Configuration config = resources.getConfiguration();
config.setLocale(locale);
resources.updateConfiguration(config, resources.getDisplayMetrics());
}
  • 注意:语言代码不能有“-”&必须只有2个小大小写字母吗

如果你写

android:configChanges="locale"

在每个活动中(在清单文件中),不需要每次输入Activity时都设置它。

我正在寻找一种方法,以编程方式改变系统语言。 虽然我完全理解一个正常的应用程序不应该这样做,而是:

  • 用户应该(通过一个意图)指向系统设置手动更改它
  • 应用程序应该自己处理本地化,就像Alex的回答中描述的那样

有必要从程序上真正改变系统的语言。

这是没有文档的API,因此不应该用于市场/最终用户应用程序!

不管怎样,这是我找到的解决方案:

  Locale locale = new Locale(targetLocaleAsString);


Class amnClass = Class.forName("android.app.ActivityManagerNative");
Object amn = null;
Configuration config = null;


// amn = ActivityManagerNative.getDefault();
Method methodGetDefault = amnClass.getMethod("getDefault");
methodGetDefault.setAccessible(true);
amn = methodGetDefault.invoke(amnClass);


// config = amn.getConfiguration();
Method methodGetConfiguration = amnClass.getMethod("getConfiguration");
methodGetConfiguration.setAccessible(true);
config = (Configuration) methodGetConfiguration.invoke(amn);


// config.userSetLocale = true;
Class configClass = config.getClass();
Field f = configClass.getField("userSetLocale");
f.setBoolean(config, true);


// set the locale to the new value
config.locale = locale;


// amn.updateConfiguration(config);
Method methodUpdateConfiguration = amnClass.getMethod("updateConfiguration", Configuration.class);
methodUpdateConfiguration.setAccessible(true);
methodUpdateConfiguration.invoke(amn, config);

这段代码真的可以工作:

fa =波斯语,en =英语

  • 注意:语言代码不能有“-”&必须只有2个小大小写字母吗

languageToLoad变量中输入你的语言代码:

import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;


public class Main extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);


String languageToLoad  = "fa"; // your language
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
this.setContentView(R.layout.main);
}
}

2021年6月更新(Kotlin):

class Main : Activity() {
// Called when the activity is first created.
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
        

val config = resources.configuration
val lang = "fa" // your language code
val locale = Locale(lang)
Locale.setDefault(locale)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
config.setLocale(locale)
else
config.locale = locale


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
createConfigurationContext(config)
resources.updateConfiguration(config, resources.displayMetrics)


this.setContentView(R.layout.main)
}
}

Locale configuration应该在每个activity中设置,然后再设置内容this.setContentView(R.layout.main);

我改变了德语为我的应用程序开始自己。

这是我的正确代码。有人想用这个来代替我吗? (如何在android中以编程方式改变语言)

我的代码:

Configuration config ; // variable declaration in globally


// this part is given inside onCreate Method starting and before setContentView()


public void onCreate(Bundle icic)
{
super.onCreate(icic);
config = new Configuration(getResources().getConfiguration());
config.locale = Locale.GERMAN ;
getResources().updateConfiguration(config,getResources().getDisplayMetrics());


setContentView(R.layout.newdesign);
}

唯一完全适合我的解决方案是结合Alex Volovoy的代码和应用程序重启机制:

void restartApplication() {
Intent i = new Intent(MainTabActivity.context, MagicAppRestart.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainTabActivity.context.startActivity(i);
}




/** This activity shows nothing; instead, it restarts the android process */
public class MagicAppRestart extends Activity {
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
finish();
}


protected void onResume() {
super.onResume();
startActivityForResult(new Intent(this, MainTabActivity.class), 0);
}
}

只是多添了一块,把我绊倒了。

而其他的答案,比如“de”,都没问题

String lang = "de";
Locale locale = new Locale(lang);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());

上面的代码不能用于例如"fr_BE"区域设置,所以它将使用values-fr-rBE文件夹或类似的文件夹。

需要以下轻微更改才能使用"fr_BE"

String lang = "fr";


//create a string for country
String country = "BE";
//use constructor with country
Locale locale = new Locale(lang, country);


Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
/*change language at Run-time*/
//use method like that:
//setLocale("en");
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);
}
创建一个类Extends Application并创建一个静态方法。 然后你可以在setContentView()之前的所有活动中调用这个方法
public class MyApp extends Application {


@Override
public void onCreate() {
super.onCreate();
}


public static void setLocaleFa (Context context){
Locale locale = new Locale("fa");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
context.getApplicationContext().getResources().updateConfiguration(config, null);
}


public static void setLocaleEn (Context context){
Locale locale = new Locale("en_US");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
context.getApplicationContext().getResources().updateConfiguration(config, null);
}


}

在活动中的使用:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyApp.setLocaleFa(MainActivity.this);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
}

您应该执行一些步骤

首先,您需要更改配置的区域设置

Resources resources = context.getResources();


Configuration configuration = resources.getConfiguration();
configuration.locale = new Locale(language);


resources.updateConfiguration(configuration, resources.getDisplayMetrics());

其次,如果希望更改直接应用于可见的布局,可以直接更新视图,也可以调用activity. rebuild()重新启动当前活动。

你还必须保留你的更改因为在用户关闭你的应用程序之后你就会失去语言更改。

我在我的博客在Android中以编程方式改变语言中解释了更详细的解决方案

基本上,你只需要在你的应用程序类上调用LocaleHelper.onCreate()如果你想动态地改变语言环境你可以调用LocaleHelper.setLocale()

我知道现在回答有点晚了,但我找到了这篇文章 . 它很好地解释了整个过程,为您提供了结构良好的代码。

Locale Helper类:

import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.preference.PreferenceManager;


import java.util.Locale;


/**
* This class is used to change your application locale and persist this change for the next time
* that your app is going to be used.
* <p/>
* You can also change the locale of your application on the fly by using the setLocale method.
* <p/>
* Created by gunhansancar on 07/10/15.
*/
public class LocaleHelper {


private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";


public static Context onAttach(Context context) {
String lang = getPersistedData(context, Locale.getDefault().getLanguage());
return setLocale(context, lang);
}


public static Context onAttach(Context context, String defaultLanguage) {
String lang = getPersistedData(context, defaultLanguage);
return setLocale(context, lang);
}


public static String getLanguage(Context context) {
return getPersistedData(context, Locale.getDefault().getLanguage());
}


public static Context setLocale(Context context, String language) {
persist(context, language);


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return updateResources(context, language);
}


return updateResourcesLegacy(context, language);
}


private static String getPersistedData(Context context, String defaultLanguage) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
}


private static void persist(Context context, String language) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();


editor.putString(SELECTED_LANGUAGE, language);
editor.apply();
}


@TargetApi(Build.VERSION_CODES.N)
private static Context updateResources(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);


Configuration configuration = context.getResources().getConfiguration();
configuration.setLocale(locale);
configuration.setLayoutDirection(locale);


return context.createConfigurationContext(configuration);
}


@SuppressWarnings("deprecation")
private static Context updateResourcesLegacy(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);


Resources resources = context.getResources();


Configuration configuration = resources.getConfiguration();
configuration.locale = locale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
configuration.setLayoutDirection(locale);
}


resources.updateConfiguration(configuration, resources.getDisplayMetrics());


return context;
}
}

您需要重写attachBaseContext并调用LocaleHelper.onAttach()来初始化应用程序中的语言环境设置。

import android.app.Application;
import android.content.Context;


import com.gunhansancar.changelanguageexample.helper.LocaleHelper;


public class MainApplication extends Application {
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocaleHelper.onAttach(base, "en"));
}
}

你所要做的就是相加

LocaleHelper.onCreate(this, "en");

只要你想改变locale。

如果你想在你的应用中保持语言变化,你必须做两件事。

首先,创建一个base Activity,让你所有的Activity都从下面扩展:

public class BaseActivity extends AppCompatActivity {


private Locale mCurrentLocale;


@Override
protected void onStart() {
super.onStart();


mCurrentLocale = getResources().getConfiguration().locale;
}


@Override
protected void onRestart() {
super.onRestart();
Locale locale = getLocale(this);


if (!locale.equals(mCurrentLocale)) {


mCurrentLocale = locale;
recreate();
}
}


public static Locale getLocale(Context context){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);


String lang = sharedPreferences.getString("language", "en");
switch (lang) {
case "English":
lang = "en";
break;
case "Spanish":
lang = "es";
break;
}
return new Locale(lang);
}
}

注意,我将新语言保存在sharedPreference中。

其次,像这样创建一个应用程序的扩展:

    public class App extends Application {


@Override
public void onCreate() {
super.onCreate();
setLocale();
}


@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setLocale();
}


private void setLocale() {


final Resources resources = getResources();
final Configuration configuration = resources.getConfiguration();
final Locale locale = getLocale(this);
if (!configuration.locale.equals(locale)) {
configuration.setLocale(locale);
resources.updateConfiguration(configuration, null);
}
}
}

注意,getLocale()与上面相同。

< p >就是这样! 我希望这能帮助到一些人。

我也面临着同样的问题。在GitHub上我找到了Android-LocalizationActivity图书馆

这个库使得在运行时更改应用程序的语言变得非常简单,如下面的代码示例所示。包含下面示例代码的示例项目和更多信息可以在github页面上找到。

LocalizationActivity扩展了AppCompatActivity,所以你也可以在使用Fragments时使用它。

public class MainActivity extends LocalizationActivity implements View.OnClickListener {


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple);


findViewById(R.id.btn_th).setOnClickListener(this);
findViewById(R.id.btn_en).setOnClickListener(this);
}


@Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.btn_en) {
setLanguage("en");
} else if (id == R.id.btn_th) {
setLanguage("th");
}
}
}

对于Android 7.0牛轧糖(或更低),请遵循这篇文章:

# EYZ0

< p > # EYZ0 < br > 这包括RTL/LTR支持:

public static void changeLocale(Context context, Locale locale) {
Configuration conf = context.getResources().getConfiguration();
conf.locale = locale;
Locale.setDefault(locale);


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
conf.setLayoutDirection(conf.locale);
}


context.getResources().updateConfiguration(conf, context.getResources().getDisplayMetrics());
}

首先为不同的语言创建多个string.xml;然后在onCreate()方法中使用这段代码:

super.onCreate(savedInstanceState);
String languageToLoad  = "fr"; // change your language here
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
this.setContentView(R.layout.main);

这是工作时,我按下按钮改变我的TextView的文本语言。(strings.xml在值-de文件夹)

String languageToLoad = "de"; // your language
Configuration config = getBaseContext().getResources().getConfiguration();
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
recreate();
Locale locale = new Locale("en");
Locale.setDefault(locale);


Configuration config = context.getResources().getConfiguration();
config.setLocale(locale);
context.createConfigurationContext(config);

重要更新:

context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());

注意,在SDK >= 21上,你需要调用' resources . updateconfiguration ()',否则资源将不会被更新。

是时候更新了。

首先,弃用列表和它被弃用的API:

  • # eyz0 (api 17)
  • # eyz0 (api 17)

# EYZ0。

createconfigationcontext是updateConfiguration的新方法。

有些人是这样独立使用的:

Configuration overrideConfiguration = ctx.getResources().getConfiguration();
Locale locale = new Locale("en_US");
overrideConfiguration.setLocale(locale);
createConfigurationContext(overrideConfiguration);

... 但这行不通。为什么?该方法返回一个上下文,然后用于处理Strings.xml翻译和其他本地化资源(图像、布局等)。

正确用法是这样的:

Configuration overrideConfiguration = ctx.getResources().getConfiguration();
Locale locale = new Locale("en_US");
overrideConfiguration.setLocale(locale);
//the configuration can be used for other stuff as well
Context context  = createConfigurationContext(overrideConfiguration);
Resources resources = context.getResources();

如果您只是复制粘贴到您的IDE中,您可能会看到一个警告,该API要求您针对API 17或更高版本。这可以通过将它放在一个方法中并添加注释@TargetApi(17)来解决

但是等待。那么旧的API呢?

您需要在没有TargetApi注释的情况下使用updateConfiguration创建另一个方法。

Resources res = YourApplication.getInstance().getResources();
// Change locale settings in the app.
DisplayMetrics dm = res.getDisplayMetrics();
android.content.res.Configuration conf = res.getConfiguration();
conf.locale = new Locale("th");
res.updateConfiguration(conf, dm);

这里不需要返回上下文。

现在,管理这些可能很困难。在API 17+中,你需要创建上下文(或者创建上下文中的资源)来获得基于本地化的适当资源。你如何处理这个问题?

好吧,我是这么做的:

/**
* Full locale list: https://stackoverflow.com/questions/7973023/what-is-the-list-of-supported-languages-locales-on-android
* @param lang language code (e.g. en_US)
* @return the context
* PLEASE READ: This method can be changed for usage outside an Activity. Simply add a COntext to the arguments
*/
public Context setLanguage(String lang/*, Context c*/){
Context c = AndroidLauncher.this;//remove if the context argument is passed. This is a utility line, can be removed totally by replacing calls to c with the activity (if argument Context isn't passed)
int API = Build.VERSION.SDK_INT;
if(API >= 17){
return setLanguage17(lang, c);
}else{
return setLanguageLegacy(lang, c);
}
}


/**
* Set language for API 17
* @param lang
* @param c
* @return
*/
@TargetApi(17)
public Context setLanguage17(String lang, Context c){
Configuration overrideConfiguration = c.getResources().getConfiguration();
Locale locale = new Locale(lang);
Locale.setDefault(locale);
overrideConfiguration.setLocale(locale);
//the configuration can be used for other stuff as well
Context context  = createConfigurationContext(overrideConfiguration);//"local variable is redundant" if the below line is uncommented, it is needed
//Resources resources = context.getResources();//If you want to pass the resources instead of a Context, uncomment this line and put it somewhere useful
return context;
}


public Context setLanguageLegacy(String lang, Context c){
Resources res = c.getResources();
// Change locale settings in the app.
DisplayMetrics dm = res.getDisplayMetrics();//Utility line
android.content.res.Configuration conf = res.getConfiguration();


conf.locale = new Locale(lang);//setLocale requires API 17+ - just like createConfigurationContext
Locale.setDefault(conf.locale);
res.updateConfiguration(conf, dm);


//Using this method you don't need to modify the Context itself. Setting it at the start of the app is enough. As you
//target both API's though, you want to return the context as you have no clue what is called. Now you can use the Context
//supplied for both things
return c;
}

这段代码的工作原理是有一个方法根据什么API调用适当的方法。这是我在许多不同的废弃调用(包括Html.fromHtml)中所做的事情。有一个方法接受所需的参数,然后将它分成两个(或三个或更多)方法之一,并根据API级别返回适当的结果。它很灵活,因为你不需要多次检查,“输入”方法为你做了。这里的入口方法是setLanguage

使用前请仔细阅读

您需要使用获取资源时返回的Context。为什么?我在这里看到了其他使用createconfigationcontext而不使用它返回的上下文的答案。为了让它这样工作,必须调用updateConfiguration。这是不赞成的。使用方法返回的上下文来获取资源。

# EYZ0:

构造函数或类似的地方:

ctx = getLanguage(lang);//lang is loaded or generated. How you get the String lang is not something this answer handles (nor will handle in the future)

然后,无论你想在哪里获得资源,你都可以:

String fromResources = ctx.getString(R.string.helloworld);

使用任何其他上下文(理论上)都会打破这一点。

AFAIK,你仍然需要使用活动上下文来显示对话框或toast。为此,您可以使用一个活动的实例(如果您在外部)


最后,在活动上使用recreate()来刷新内容。快捷方式可以不用创建意图刷新。

# EYZ1 # EYZ2。您需要下载文章中提到的LocaleHelper.java

  1. 创建将扩展ApplicationMyApplication
  2. 覆盖attachBaseContext()来更新语言。
  3. 在manifest中注册这个类。

    public class MyApplication extends Application {
    @Override
    protected void attachBaseContext(Context base) {
    super.attachBaseContext(LocaleHelper.onAttach(base, "en"));
    }
    }
    
    
    <application
    android:name="com.package.MyApplication"
    .../>
    
  4. Create BaseActivity and override onAttach() to update language. Needed for Android 6+

    public class BaseActivity extends Activity {
    @Override
    protected void attachBaseContext(Context base) {
    super.attachBaseContext(LocaleHelper.onAttach(base));
    }
    }
    
  5. Make all activities on your app extends from BaseActivity.

    public class LocaleHelper {
    
    
    private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";
    
    
    public static Context onAttach(Context context) {
    String lang = getPersistedData(context, Locale.getDefault().getLanguage());
    return setLocale(context, lang);
    }
    
    
    public static Context onAttach(Context context, String defaultLanguage) {
    String lang = getPersistedData(context, defaultLanguage);
    return setLocale(context, lang);
    }
    
    
    public static String getLanguage(Context context) {
    return getPersistedData(context, Locale.getDefault().getLanguage());
    }
    
    
    public static Context setLocale(Context context, String language) {
    persist(context, language);
    
    
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    return updateResources(context, language);
    }
    
    
    return updateResourcesLegacy(context, language);
    }
    
    
    private static String getPersistedData(Context context, String defaultLanguage) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
    }
    
    
    private static void persist(Context context, String language) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = preferences.edit();
    
    
    editor.putString(SELECTED_LANGUAGE, language);
    editor.apply();
    }
    
    
    @TargetApi(Build.VERSION_CODES.N)
    private static Context updateResources(Context context, String language) {
    Locale locale = new Locale(language);
    Locale.setDefault(locale);
    
    
    Configuration configuration = context.getResources().getConfiguration();
    configuration.setLocale(locale);
    configuration.setLayoutDirection(locale);
    
    
    return context.createConfigurationContext(configuration);
    }
    
    
    @SuppressWarnings("deprecation")
    private static Context updateResourcesLegacy(Context context, String language) {
    Locale locale = new Locale(language);
    Locale.setDefault(locale);
    
    
    Resources resources = context.getResources();
    
    
    Configuration configuration = resources.getConfiguration();
    configuration.locale = locale;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
    configuration.setLayoutDirection(locale);
    }
    
    
    resources.updateConfiguration(configuration, resources.getDisplayMetrics());
    
    
    return context;
    }
    }
    

下面是一些适合我的代码:

public class  MainActivity extends AppCompatActivity {
public static String storeLang;


@Override
protected void onCreate(Bundle savedInstanceState) {


SharedPreferences shp = PreferenceManager.getDefaultSharedPreferences(this);
storeLang = shp.getString(getString(R.string.key_lang), "");


// Create a new Locale object
Locale locale = new Locale(storeLang);


// Create a new configuration object
Configuration config = new Configuration();
// Set the locale of the new configuration
config.locale = locale;
// Update the configuration of the Accplication context
getResources().updateConfiguration(
config,
getResources().getDisplayMetrics()
);


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

来源:# EYZ0

这里列出的解决方案没有一个对我有用。

如果AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES),语言没有在android >= 7.0上切换

这个LocaleUtils工作得很好: # EYZ0 < / p >

LocaleUtils

public class LocaleUtils {


public static final String LAN_SPANISH      = "es";
public static final String LAN_PORTUGUESE   = "pt";
public static final String LAN_ENGLISH      = "en";


private static Locale sLocale;


public static void setLocale(Locale locale) {
sLocale = locale;
if(sLocale != null) {
Locale.setDefault(sLocale);
}
}


public static void updateConfig(ContextThemeWrapper wrapper) {
if(sLocale != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
Configuration configuration = new Configuration();
configuration.setLocale(sLocale);
wrapper.applyOverrideConfiguration(configuration);
}
}


public static void updateConfig(Application app, Configuration configuration) {
if(sLocale != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
//Wrapping the configuration to avoid Activity endless loop
Configuration config = new Configuration(configuration);
config.locale = sLocale;
Resources res = app.getBaseContext().getResources();
res.updateConfiguration(config, res.getDisplayMetrics());
}
}
}

将此代码添加到应用程序

public class App extends Application {
public void onCreate(){
super.onCreate();


LocaleUtils.setLocale(new Locale("iw"));
LocaleUtils.updateConfig(this, getBaseContext().getResources().getConfiguration());
}


@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
LocaleUtils.updateConfig(this, newConfig);
}
}

活动中的代码

public class BaseActivity extends AppCompatActivity {
public BaseActivity() {
LocaleUtils.updateConfig(this);
}
}

添加LocaleHelper

public class LocaleHelper{
private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";
public static Context onAttach(Context context) {
String lang = getPersistedData(context, Locale.getDefault().getLanguage());
return setLocale(context, lang);
}


public static Context onAttach(Context context, String defaultLanguage) {
String lang = getPersistedData(context, defaultLanguage);
return setLocale(context, lang);
}


public static String getLanguage(Context context) {
return getPersistedData(context, Locale.getDefault().getLanguage());
}
public static Context setLocale(Context context, String language) {
persist(context, language);


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return updateResources(context, language);
}


return updateResourcesLegacy(context, language);
}


private static String getPersistedData(Context context, String defaultLanguage) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
}


private static void persist(Context context, String language) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();


editor.putString(SELECTED_LANGUAGE, language);
editor.apply();
}


@TargetApi(Build.VERSION_CODES.N)
private static Context updateResources(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);


Configuration configuration = context.getResources().getConfiguration();
configuration.setLocale(locale);
configuration.setLayoutDirection(locale);


return context.createConfigurationContext(configuration);
}


@SuppressWarnings("deprecation")
private static Context updateResourcesLegacy(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);


Resources resources = context.getResources();


Configuration configuration = resources.getConfiguration();
configuration.locale = locale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
configuration.setLayoutDirection(locale);
}


resources.updateConfiguration(configuration, resources.getDisplayMetrics());


return context;
}
}

在活动或片段中

Context context = LocaleHelper.setLocale(this, App.getSharedPre().getLanguage());
Resource resources = context.getResources();

现在在每个文本上设置文本

TextView tv = findViewById(R.id.tv);
tv.setText(resources.getString(R.string.tv));

阿拉伯语/RTL支持

  1. 您必须通过- attachBaseContext()更新您的语言设置。
  2. 对于android版本N及以上,您必须使用createconfigationcontext () &updateConfiguration() -否则RTL布局不能正常工作

 @Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(updateBaseContextLocale(newBase));
}


public Context updateBaseContextLocale(Context context) {
String language = SharedPreference.getInstance().getValue(context, "lan");//it return "en", "ar" like this
if (language == null || language.isEmpty()) {
//when first time enter into app (get the device language and set it
language = Locale.getDefault().getLanguage();
if (language.equals("ar")) {
SharedPreference.getInstance().save(mContext, "lan", "ar");
}
}
Locale locale = new Locale(language);
Locale.setDefault(locale);


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
updateResourcesLocale(context, locale);
return  updateResourcesLocaleLegacy(context, locale);
}


return updateResourcesLocaleLegacy(context, locale);
}


@TargetApi(Build.VERSION_CODES.N)
private Context updateResourcesLocale(Context context, Locale locale) {
Configuration configuration = context.getResources().getConfiguration();
configuration.setLocale(locale);
return context.createConfigurationContext(configuration);
}


@SuppressWarnings("deprecation")
private Context updateResourcesLocaleLegacy(Context context, Locale locale) {
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
configuration.locale = locale;
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
return context;
}

我终于弄清楚如何设置它工作在两个=N安卓版本。

用你自己的抽象类扩展AppCompatActivity,比如:

abstract class MLAppCompatActivity : AppCompatActivity() {
override fun attachBaseContext(newBase: Context?) {
super.attachBaseContext(LocaleHelper.wrap(newBase))
}


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
LocaleHelper.wrap(this)
}
}
}

attachBaseContext在Android >=N个版本上被调用,这样activity将使用正确的上下文。在Android <N上,我们必须以另一种方式调用这个函数,在设置内容视图之前。因此,我们重写onCreate函数来设置正确的上下文。 意思是,每当你创建一个新的Activity时,你必须扩展你的抽象类。比如这个:

class TermsActivity : MLAppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_terms)
}
}

最后LocaleHelper是这样的:

import android.annotation.TargetApi;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.util.DisplayMetrics;


import com.at_zone.constants.SharedPreferencesKeys;


import java.util.Locale;


public class LocaleHelper extends ContextWrapper {


public LocaleHelper(Context base) {
super(base);
}


public static Context wrap(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences(
SharedPreferencesKeys.SHARED_PREFERENCES, Context.MODE_PRIVATE
);
String language = sharedPreferences.getString(SharedPreferencesKeys.CURRENT_LANGUAGE, "default");
if (!language.equals("default")) {
Configuration config = context.getResources().getConfiguration();
if (!language.equals("")) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
setSystemLocale(config, locale);
} else {
setSystemLocaleLegacy(context, config, locale);
}
config.setLayoutDirection(locale);
context = context.createConfigurationContext(config);
}
return new LocaleHelper(context);
}
return context;
}


public static String getSystemLanguage(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return getSystemLocale(context).getLanguage().toLowerCase();
} else {
return getSystemLocaleLegacy(context).getLanguage().toLowerCase();
}
}


public static Locale getSystemLocaleLegacy(Context context) {
Configuration config = context.getResources().getConfiguration();
return config.locale;
}


@TargetApi(Build.VERSION_CODES.N)
public static Locale getSystemLocale(Context context) {
return context.getResources().getConfiguration().getLocales().get(0);
}


public static void setSystemLocaleLegacy(Context context, Configuration config, Locale locale) {
config.locale = locale;
Resources res = context.getResources();
DisplayMetrics dm = res.getDisplayMetrics();
res.updateConfiguration(config, dm);
}


@TargetApi(Build.VERSION_CODES.N)
public static void setSystemLocale(Configuration config, Locale locale) {
config.setLocale(locale);
}


}
对我来说,最好的解决方案是: # EYZ0 < / p >
package me.mehadih.multiplelanguage;


import androidx.appcompat.app.AppCompatActivity;


import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;


import java.util.Locale;


public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setApplicationLocale("az"); // short name of language. "en" for English
setContentView(R.layout.activity_main);


}


private void setApplicationLocale(String locale) {
Resources resources = getResources();
DisplayMetrics dm = resources.getDisplayMetrics();
Configuration config = resources.getConfiguration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
config.setLocale(new Locale(locale.toLowerCase()));
} else {
config.locale = new Locale(locale.toLowerCase());
}
resources.updateConfiguration(config, dm);
}
}
对于androidx.appcompat: appcompat用户,上述解决方案将在1.3.0版本后生效。

.

.

您可以要求用户在第一个屏幕中选择语言,并将其保存在SharedPreferences

SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
editor.putString("lang", "si");
editor.apply();
    

recreate();

然后您可以在应用程序中的每个Activity中使用它。这里我设置了英语和僧伽罗语。

@Override
protected void attachBaseContext(Context base) {
SharedPreferences prefs = base.getSharedPreferences("uinfo", MODE_PRIVATE);
String restoredText = prefs.getString("lang", "No name defined");


if (restoredText.equals("si")){
super.attachBaseContext(LocaleHelper.localeUpdateResources(base, "si"));
}else{
super.attachBaseContext(LocaleHelper.localeUpdateResources(base, "en"));
}
}

这是你的localUpdateResources方法。把它放在LocalHelper类中

public class LocaleHelper {
public static Context localeUpdateResources(Context context, String languageCode) {


Context newContext = context;


Locale locale = new Locale(languageCode);
Locale.setDefault(locale);


Resources resources = context.getResources();
Configuration config = new Configuration(resources.getConfiguration());


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {


config.setLocale(locale);
newContext = context.createConfigurationContext(config);


} else {


config.locale = locale;
resources.updateConfiguration(config, resources.getDisplayMetrics());
}


return newContext;


}
}

Resources.updateConfiguration()已经是弃用,我已经解决了这个没有创建任何自定义ContextWrapper

首先我创建了一个扩展函数

fun Context.setAppLocale(language: String): Context {
val locale = Locale(language)
Locale.setDefault(locale)
val config = resources.configuration
config.setLocale(locale)
config.setLayoutDirection(locale)
return createConfigurationContext(config)
}

然后在活动的attachBaseContext方法中,简单地用新的上下文替换上下文。

override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(ContextWrapper(newBase.setAppLocale("bn")))
}

对每个应用语言偏好的支持刚刚添加到API 33 (Android 13,提拉米苏目前在开发人员预览版)。

要改变应用程序的区域设置,只需从LocaleManager调用setApplicationLocales:

// Set app locale to pt-BR (Portuguese, Brazil)
getSystemService(LocaleManager::class.java)
.applicationLocales = LocaleList(Locale.forLanguageTag("pt-BR"))

详见https://developer.android.com/about/versions/13/features/app-languages#api-impl

我曾经写过一篇关于这个功能https://proandroiddev.com/exploring-the-new-android-13-per-app-language-preferences-8d99b971b578的文章

如果你正在使用片段,并且你想在Android中以编程方式更改应用程序语言,请使用此方法

  public void setLocale(Activity activity, String languageCode) {
Locale locale = new Locale(languageCode);
Locale.setDefault(locale);
Resources resources = activity.getResources();
Configuration config = resources.getConfiguration();
config.setLocale(locale);
resources.updateConfiguration(config, resources.getDisplayMetrics());
SettingsFragment settingsFragment = new SettingsFragment();
FragmentManager fragmentManager = requireActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
activity.overridePendingTransition(0,0);
fragmentTransaction.replace(R.id.main, settingsFragment).commit();
}

这样叫它

setLocale(requireActivity(),"fr");
只要用你的片段名改变SettingsFragment,在你调用方法的地方,这基本上刷新了布局以获得视图上的新字符串 如果你想在另一个类上设置这个方法,只需添加这样的context

public void setLocale(Activity activity, String languageCode,Context context) {
Locale locale = new Locale(languageCode);
Locale.setDefault(locale);
Resources resources = activity.getResources();
Configuration config = resources.getConfiguration();
config.setLocale(locale);
resources.updateConfiguration(config, resources.getDisplayMetrics());
SettingsFragment settingsFragment = new SettingsFragment();
FragmentManager fragmentManager = ((AppCompatActivity) context).getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
activity.overridePendingTransition(0,0);
fragmentTransaction.replace(R.id.main, settingsFragment).commit();
}

这个功能是由谷歌为Android 13正式推出的(也有向后支持)。Android现在允许你为每个应用程序选择语言。

官方文件在这里- https://developer.android.com/guide/topics/resources/app-languages

要设置用户的首选语言,你会要求用户在语言选择器中选择一个地区,然后在系统中设置该值:

// 1. Inside an activity, in-app language picker gets an input locale "xx-YY"
// 2. App calls the API to set its locale
mContext.getSystemService(LocaleManager.class
).setApplicationLocales(newLocaleList(Locale.forLanguageTag("xx-YY")));
// 3. The system updates the locale and restarts the app, including any configuration updates
// 4. The app is now displayed in "xx-YY" language

要在语言选择器中显示用户当前的首选语言,你的应用程序可以从系统中获取返回的值:


// 1. App calls the API to get the preferred locale
LocaleList currentAppLocales =
mContext.getSystemService(LocaleManager.class).getApplicationLocales();
// 2. App uses the returned LocaleList to display languages to the user