android代码更改语言,Android N以编程方式更改语言

受各种代码的启发(例如:我们的Stackoverflow团队(大声疾呼)),我制作了一个简单得多的版本。该ContextWrapper扩展名是不必要的。

首先,假设您有2个按钮用于2种语言,即EN和KH。在按钮的onClick中,将语言代码保存到中SharedPreferences,然后调用activity recreate()方法。

例:

@Override

public void onClick(View v) {

switch(v.getId()) {

case R.id.btn_lang_en:

//save "en" to SharedPref here

break;

case R.id.btn_lang_kh:

//save "kh" to SharedPref here

break;

default:

break;

}

getActivity().recreate();

}

然后创建一个ContextWrapper可能在Utils类中返回的静态方法(这就是我所做的,lul)。

public static ContextWrapper changeLang(Context context, String lang_code){

Locale sysLocale;

Resources rs = context.getResources();

Configuration config = rs.getConfiguration();

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

sysLocale = config.getLocales().get(0);

} else {

sysLocale = config.locale;

}

if (!lang_code.equals("") && !sysLocale.getLanguage().equals(lang_code)) {

Locale locale = new Locale(lang_code);

Locale.setDefault(locale);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

config.setLocale(locale);

} else {

config.locale = locale;

}

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {

context = context.createConfigurationContext(config);

} else {

context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());

}

}

return new ContextWrapper(context);

}

最后,从加载的语言代码SharedPreferences中的所有活动'S attachBaseContext(Context newBase)方法。

@Override

protected void attachBaseContext(Context newBase) {

String lang_code = "en"; //load it from SharedPref

Context context = Utils.changeLang(newBase, lang_code);

super.attachBaseContext(context);

}

奖励:为了节省键盘上的汗水,我创建了一个LangSupportBaseActivity类,扩展了类Activity并在其中使用最后一块代码。并且我将所有其他活动扩展LangSupportBaseActivity。

例:

public class LangSupportBaseActivity extends Activity{

...blab blab blab so on and so forth lines of neccessary code

@Override

protected void attachBaseContext(Context newBase) {

String lang_code = "en"; //load it from SharedPref

Context context = Utils.changeLang(newBase, lang_code);

super.attachBaseContext(context);

}

}

public class HomeActivity extends LangSupportBaseActivity{

...blab blab blab

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值