网上流行几种多语言的切换,但可能是作者对Android的理解有所偏差,所以某些地方上存在者一点错误,走了弯路。
在开始之前,大家不妨先看一下不是太好的3种方法吧(这里只是探讨更好的方法,为精简本文篇幅,故引用原博客,本人对原博客作者并无不敬之处,相反,对于原作者的贡献精神以及早期资料搜集的引导非常尊重)。
##########################################################################################
1、代码以及效果图
package com.example.newthingstest;
import java.util.Locale;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.widget.TextView;
public class ActivityLanguage extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
final TextView tv = new TextView(this) ;
tv.setText(R.string.lang_test);
tv.postDelayed(new Runnable() {
@Override
public void run() {
setResoucesLocale(Locale.CHINESE) ;
tv.setText(R.string.lang_test);
}
}, 3000) ;
tv.setTextColor(0xFFFF0000);
tv.setBackgroundResource(android.R.color.black);
setContentView(tv) ;
}
protected void setResoucesLocale(Locale loc) {
Configuration config = this.getResources().getConfiguration() ;
config.locale = loc ;
this.getResources().updateConfiguration(config, this.getResources().getDisplayMetrics());
}
}
本人使用的是模拟器测试的,默认语言是English。
效果如下
2、代码分析
Configuration config = this.getResources().getConfiguration() ;
config.locale = loc ;
this.getResources().updateConfiguration(config, this.getResources().getDisplayMetrics());
首先获取当前系统中的Configuration,并修改其中的locale属性,然后调用updateConfiguration(),注意,这是关键,这里之前的开发者误以为是更新UI,其实这里这是更新ID对资源的引用,如之前指向的是values-en文件夹内的string.xml,修改后指向values-zh内的string.xml