18034727885
2026-07-09 c26d344da4c54ad8456a2dc145cde0b424722f0e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.driver.igotrip.utils;
 
import android.content.Context;
import android.content.res.Configuration;
import android.os.Build;
import android.os.LocaleList;
import android.text.TextUtils;
import android.util.Log;
 
import java.util.Locale;
 
public class LanguageManager {
 
    /**
     * 为 Application/Activity 提供经过语言配置的 Context
     * 必须在 attachBaseContext 中调用
     */
    public static Context wrapContext(Context context) {
        String language = LanguageSP.getLanguage(context);
        Log.e("语言: ", language);
        // 否则根据保存的语言配置 Context
        return updateContextLocale(context, language);
    }
 
    /**
     * 更新 Context 的语言配置(适配全版本)
     */
    private static Context updateContextLocale(Context context, String language) {
        Locale targetLocale = getLocaleFromLanguage(language);
        Configuration configuration = context.getResources().getConfiguration();
 
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // 7.0+ 用 LocaleList 配置
            configuration.setLocales(new LocaleList(targetLocale));
            // 创建新的 Context(必须用 createConfigurationContext,否则不生效)
            return context.createConfigurationContext(configuration);
        } else {
            // 7.0 以下直接设置 locale
            configuration.locale = targetLocale;
            // 更新资源配置
            context.getResources().updateConfiguration(
                    configuration,
                    context.getResources().getDisplayMetrics()
            );
            return context;
        }
    }
 
    /**
     * 将语言字符串(如 "zh-CN")转换为 Locale 对象
     */
    private static Locale getLocaleFromLanguage(String language) {
        if (TextUtils.isEmpty(language)) {
            return Locale.FRENCH;
        }
        String[] parts = language.split("-");
        if (parts.length == 1) {
            return new Locale(parts[0]); // 如 Const.Language.ENGLISH -> Locale(Const.Language.ENGLISH)
        } else {
            return new Locale(parts[0], parts[1]); // 如 "zh-CN" -> Locale("zh", "CN")
        }
    }
}