You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用setLocale()函数时如何获取当前Locale语言值?

解决方案

一、在setLocale函数中获取当前Locale值

你有两种可靠的方式获取当前Locale:

  • 直接复用你创建的myLocale对象(这就是你刚设置的目标Locale)
  • 从应用资源配置中读取已生效的Locale(验证设置结果)

修改后的setLocale函数示例:

// main.java
public void setLocale(String lang) {
    Locale myLocale = new Locale(lang);
    Resources res = getResources();
    DisplayMetrics dm = res.getDisplayMetrics();
    Configuration conf = res.getConfiguration();
    conf.locale = myLocale;
    res.updateConfiguration(conf, dm);
    
    // 方式1:直接使用创建好的myLocale
    String currentLangCode = myLocale.getLanguage();
    
    // 方式2:从配置中读取生效的Locale(和myLocale一致)
    Locale activeLocale = conf.locale;
    
    // 将语言信息传递到下一个页面
    Intent refresh = new Intent(this, MainActivity2.class);
    refresh.putExtra("SELECTED_LANG_CODE", currentLangCode);
    finish();
    startActivity(refresh);
}

二、在另一个Java文件中实现数据表选择逻辑

在目标页面(比如MainActivity2)中接收传递的语言代码,然后通过if-else判断选择对应的数据表:

// MainActivity2.java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    
    // 获取传递的语言代码
    String langCode = getIntent().getStringExtra("SELECTED_LANG_CODE");
    
    // 数据表选择逻辑
    String targetTable;
    if ("en".equals(langCode)) {
        // 英语选择英语数据表
        targetTable = "english_data_table";
    } else {
        // 其他语言匹配对应数据表(可根据实际需求调整映射规则)
        targetTable = langCode + "_data_table";
    }
    
    // 后续使用targetTable操作对应的数据表
}

补充提示

如果需要让语言设置在App重启后仍然生效,建议将语言代码保存到SharedPreferences中,App启动时读取并自动设置,这样其他页面无需通过Intent传递,直接从SharedPreferences读取即可。

内容的提问来源于stack exchange,提问作者James Black

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 15:51:54