Kotlin图文讲解多语言支持实现方法

Kefira ·
更新时间:2024-09-20
· 1850 次阅读

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>

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

到此这篇关于Kotlin图文讲解多语言支持实现方法的文章就介绍到这了,更多相关Kotlin多语言支持内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!



多语言 Kotlin 方法

需要 登录 后方可回复, 如果你还没有账号请 注册新账号
相关文章