LVGL Pro使用指南[14] LVGL XML 多语言

概述 链接到标题

LVGL 的 XML 翻译模块允许在 XML 文件中直接定义和使用翻译字符串。该模块基于 LVGL 的翻译模块构建,可用于支持多语言翻译功能。

使用方法 链接到标题

在 XML 文件中,使用 <translations> 标签定义翻译内容。<translations> 标签的 languages 属性指定支持的语言,例如 languages="en de hu"

每个 <translation> 标签定义一个翻译条目,包含一个 tag 属性(作为查找键)和每种语言的翻译内容。翻译可以单独放到一个 translation.xml 文件中,也可以有多个 XML 翻译文件;这些 XML 文件会被整合到一起并统一检索

示例:定义了英语和德语两种语言的翻译字符串

<translations languages="en de">
	<translation tag="dog" char_count="40" en="This is a dog" de="Das ist ein Hund" />
	<translation tag="cat" char_count="40" en="A curious little cat" de="Eine neugierige kleine Katze" />
	<translation tag="house" char_count="40" en="The house is cozy and warm" de="Das Haus ist gemütlich und warm" />
	<translation
		char_count="60"
		tag="person"
		en="A kind person with a bright smile"
		de="Eine freundliche Person mit einem strahlenden Lächeln"
	/>
</translations>

当 LVGL Pro Editor 导出 XML 代码为 C 时,会生成代码自动注册翻译字符串:

static const char * translation_languages[] = {"en", "de", NULL};
static const char * translation_tags[] = {"dog", "cat", "house", "person", NULL};
static const char * translation_texts[] = {
    "This is a dog", "Das ist ein Hund", /* dog */
    "A curious little cat", "Eine neugierige kleine Katze", /* cat */
    "The house is cozy and warm", "Das Haus ist gemütlich und warm", /* house */
    "A kind person with a bright smile", "Eine freundliche Person mit einem strahlenden Lächeln", /* person */
};

lv_translation_add_static(translation_languages, translation_tags, translation_texts);

但是目标 XML 并不支持多语言和 subject 绑定,也就是无法直接使用 XML 来控制翻译,需要在 C 代码中手动调用 lv_translation_set_language 来设置当前语言。

例如设置为英语就是 lv_translation_set_language("en");,而德语就是 lv_translation_set_language("de");。调用 API 设置当前语言后,UI 会立即生效。

当某种语言的翻译内容缺失时,系统会自动回退到默认语言或其他已定义的语言,回退规则与 LVGL 的翻译模块相同。

参考 链接到标题

https://docs.lvgl.io/master/xml/features/translations.html