最近工作中突然要求要项目进行国际化,之前没遇到过。但是也很简单呀,只需要把添加一个相应语言的的strings.xml的资源文件就好了
创建values
这里准备创建资源
点击ok 一个英文的values包就创好了
接下里 我们需要在新建的values中创建string.xml 文件 并与默认values包中的string保持一致
xml布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="中文"
android:id="@+id/china"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="英文"
android:id="@+id/english"
android:layout_marginTop="40dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/login"
android:id="@+id/tv"/>
</RelativeLayout>
Activity中
@Override
protected void onResume() {
super.onResume();
tv.setText(R.string.login);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.china:
updateActivity("zh");
break;
case R.id.english:
updateActivity("en");
break;
}
}
public void updateActivity(String sta){
Locale myLocale = new Locale(sta);
Resources res = getResources();// 获得res资源对象
DisplayMetrics dm = res.getDisplayMetrics();// 获得屏幕参数:主要是分辨率,像素等。
Configuration conf = res.getConfiguration();// 获得设置对象
conf.locale = myLocale;// 简体中文
res.updateConfiguration(conf, dm);
Intent intent = new Intent(MainActivity.this,MainActivity.class);
startActivity(intent);
}
当资源的语言改变时,要重新调用tv.setText()方法界面才会生效
当前Activity中我用的模式是singTop 当跳转自身时会执行onPause–onNewInstanse–onResume 所以我就将tv.setText() 中写到了 onResume中