多语言适配是工作中经常要用到的,为了怕自己遗忘,也为了大家了解一下多语言适配,写了这篇博客,话不多说-------------开始吧。
多语言适配分三步 : 1,新建values文件 2,Java代码 3,刷新页面
一,新建不同语言的Values文件
第一步,把左边的工作区间切换到project , 找到res文件夹下的values 文件夹 复制 , 粘贴到res文件架下面重新命名
如下图:
点击确定后,在res多出对应文件夹 至于为什么这么命名 过一会解释~
如下图:
colors.xml 和 styles.xml 没有用 删掉
打开两个 strings.xml 新增一条string 方便一会确认
在来个英文的吧
values-en
第一步基本完成 不过顺道把 布局文件做一下简单设置吧
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
android:orientation="vertical"
tools:context="com.example.administrator.q.MainActivity">
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="@string/asd"
android:textSize="40sp"
/>
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@null"
android:text="刷新按钮"
android:textSize="40sp"/>
</LinearLayout>
二 , Java 代码
Resources resources = getResources();
//获取系统的配置
Configuration config = resources.getConfiguration();
DisplayMetrics dm = resources.getDisplayMetrics();
//将语言设置成简体中文
config.locale = Locale.CHINESE;
resources.updateConfiguration(config, dm);
倒数第二行 Locale. 后面跟的什么语言就是什么语言 如果你新建了中文values-zh-rCN 这个会变成系统默认
换成 Locale.CHINESE 就会变成你一刚开始 系统自带的strings.xml
换完之后运行一下 发现没有换成自己设置的语言???
为什么呢 ------ 因为没有刷新页面 - - 。
三,刷新页面
上面的布局文件 里面有个Button记得吗??
在Java代码里面 设置点击事件
里面代码如下
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
overridePendingTransition(0,0);
}
});
跳转动画太难看了 , 我就取消了 变成闪一下的 ------
好了 现在运行是不是语言就换了呢 哈哈
那么现在问题就来了~~~~~~不同语言对应的不同values文件夹应该怎么命名呢?
这是个好问题
详情看下一片博客
88