Kotlin 32. Kotlin 多语言支持

Kotlin 多语言支持

对于 Kotlin 来说,当我们新建一个项目时,会默认在 values/ 文件夹下,生成一个 strings.xml 文件。比如说,

<resources>
    <string name="app_name">exampleNewProject</string>
</resources>

当我们在 activity_main.xml 中,添加一个按钮,比如。我们需要给这个按钮设置一个Text,比如:PRESS ME。

<Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="PRESS ME" />

这个时候,系统就会提醒我们,要这么写:

<Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/press_me" />

回到 strings.xml 文件,我们发现,多了一条:

<resources>
    <string name="app_name">notificationSoundPlay</string>
    <string name="press_me">PRESS ME</string>
</resources>

所以,我们只需要修改这里的各个string变量的值,对应文件中的值即会发生改变。

那么,下一个问题来了,我们如何支持多语言APP呢?即,如果我们设置APP语言为中文,当我们再次打开这个APP时,如何会显示带着中文的按钮呢?

我们右键 resNewAndroid Resource File

请添加图片描述

点击 Locale

请添加图片描述

找到 Chinese 的选项,然后如下图所示,新建一个 string.xml 文件。文件名还是一样的,但它和上面那个 string.xml 不在一个文件夹下。

请添加图片描述

新建的 string.xml 里面基本是空的,如下图:

请添加图片描述

我们能看到,这个 string.xml 后面有一个淡淡的 (zh)。

最后,我们将需要转化的string变量写在这里,并翻译成中文即可:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="press_me">点我</string>
</resources>
``

(需要注意,我们将手机的系统语言换成中文之后,才会看到这个包含中文的按钮)

猜你喜欢

转载自blog.csdn.net/zyctimes/article/details/129051542
今日推荐