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


当前回答

您可以从当前区域“提取”语言。你可以通过标准的Java API或者使用Android Context来提取语言环境。例如,下面这两行是等价的:

String locale = context.getResources().getConfiguration().locale.getDisplayName();
String locale = java.util.Locale.getDefault().getDisplayName();

其他回答

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

if(Locale.getDefault().getDisplayName().equals("हिन्दी (भारत)")){
    // your code here
}

我的解是这样的

@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());
            }

显示——>和

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()));

你可以尝试从系统资源中获取locale:

PackageManager packageManager = context.getPackageManager();
Resources resources = packageManager.getResourcesForApplication("android");
String language = resources.getConfiguration().locale.getLanguage();