lmw
2023-03-10 28ebc366edb1509b224ce443757038ea07fe5a6f
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
64
65
66
67
package cn.sinata.xldutils.utils;
 
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.LocaleList;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
 
import java.util.Locale;
 
import static android.content.ContentValues.TAG;
 
public class LanguageUtil {
    public static Context attachBaseContext(Context context, String language, String country) {
        Log.d(TAG, "attachBaseContext: "+ Build.VERSION.SDK_INT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return updateResources(context, language,country);
        } else {
            return context;
        }
    }
 
    @TargetApi(Build.VERSION_CODES.N)
    private static Context updateResources(Context context, String language, String country) {
        Resources resources = context.getResources();
        Locale locale = new Locale(language,country);
 
        Configuration configuration = resources.getConfiguration();
        configuration.setLocale(locale);
        configuration.setLocales(new LocaleList(locale));
        return context.createConfigurationContext(configuration);
    }
 
    /**
     * @param context
     * @param newLanguage 想要切换的语言类型 比如 "en" ,"zh"
     */
    @SuppressWarnings("deprecation")
    public static void changeAppLanguage(Context context, String newLanguage, String country) {
        if (TextUtils.isEmpty(newLanguage)) {
            return;
        }
        Resources resources = context.getResources();
        Configuration configuration = resources.getConfiguration();
        //获取想要切换的语言类型
        Locale locale = new Locale(newLanguage,country);
        configuration.setLocale(locale);
        // updateConfiguration
        DisplayMetrics dm = resources.getDisplayMetrics();
        resources.updateConfiguration(configuration, dm);
    }
 
    /**
     * 如果是7.0以下,我们需要调用changeAppLanguage方法,
     * 如果是7.0及以上系统,直接把我们想要切换的语言类型保存在SharedPreferences中,然后重新启动MainActivity即可
     */
    public static void setLanguage(String language,String country,Context appContext){
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            LanguageUtil.changeAppLanguage(appContext, language,country);
        }
        SPUtils.Companion.instance().put("language",language).put("country",country).apply();
    }
}