如何在Android设备中选择当前语言?


当前回答

你可以使用 .getLanguage .setLanguage (Locale.forLanguageTag (Locale.getDefault () ())); 这很好

其他回答

以上答案没有区分简体中文和繁体中文。 Locale.getDefault(). tostring()工作,返回“zh_CN”,“zh_TW”,“en_US”等。

参考:https://developer.android.com/reference/java/util/Locale.html, ISO 639-1是旧的。

public class LocalUtils {

    private static final String LANGUAGE_CODE_ENGLISH = "en";


    // returns application language eg: en || fa ...
    public static String getAppLanguage() {
        return Locale.getDefault().getLanguage();
    }

    // returns device language eg: en || fa ...
    public static String getDeviceLanguage() {
        return ConfigurationCompat.getLocales(Resources.getSystem().getConfiguration()).get(0).getLanguage();
    }

    public static boolean isDeviceEnglish() {
        return getDeviceLanguage().equals(new Locale(LANGUAGE_CODE_ENGLISH).getLanguage());
    }

    public static boolean isAppEnglish() {
        return getAppLanguage().equals(new Locale(LANGUAGE_CODE_ENGLISH).getLanguage());
    }


}

Log.i("AppLanguage: ",     LocalUtils.getAppLanguage());
Log.i("DeviceLanguage: ",  LocalUtils.getDeviceLanguage());
Log.i("isDeviceEnglish: ", String.valueOf(LocalUtils.isDeviceEnglish()));
Log.i("isAppEnglish: ",    String.valueOf(LocalUtils.isAppEnglish()));

我的解是这样的

@SuppressWarnings("deprecation")
public String getCurrentLocale2() {
    return Resources.getSystem().getConfiguration().locale.getLanguage();
}

@TargetApi(Build.VERSION_CODES.N)
public Locale getCurrentLocale() {
    getResources();
    return Resources.getSystem().getConfiguration().getLocales().get(0);
}

然后

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Log.e("Locale", getCurrentLocale().getLanguage());
            } else {
                Log.e("Locale", getCurrentLocale2().toString());
            }

显示——>和

下面是获取设备国家的代码。兼容所有版本的android甚至奥利奥。

解决方案:如果用户没有sim卡,那么在手机设置或当前语言选择时获取他所使用的国家。

public static String getDeviceCountry(Context context) {
    String deviceCountryCode = null;

    final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

        if(tm != null) {
            deviceCountryCode = tm.getNetworkCountryIso();
        }

    if (deviceCountryCode != null && deviceCountryCode.length() <=3) {
        deviceCountryCode = deviceCountryCode.toUpperCase();
    }
    else {
        deviceCountryCode = ConfigurationCompat.getLocales(Resources.getSystem().getConfiguration()).get(0).getCountry().toUpperCase();
    }

  //  Log.d("countryCode","  : " + deviceCountryCode );
    return deviceCountryCode;
}

为了节省其他人的时间和/或混乱,我想分享我已经尝试了上面Johan Pelgrim提出的两个替代方案,在我的设备上它们是等效的——无论默认位置是否改变。

所以我的设备的默认设置是英语(英国),在这种状态下,约翰的回答中的两个字符串都给出了相同的结果。如果我然后在电话设置中更改区域设置(说到italiano(意大利))并重新运行,那么在Johan的回答中两个字符串都将区域设置为italiano(意大利)。

因此,我认为Johan最初的帖子是正确的,而gregm的评论是不正确的。