Android - 枚举的本地化

Android - localization of an enum

我必须将待办事项应用程序翻译成多种语言。

我有一个包含 3 个级别(低、中、高)的枚举,我还用它来引用优先级标签。这是它的样子:

public enum Priority {
    LOW(R.drawable.priority_low),
    MEDIUM(R.drawable.priority_medium),
    HIGH(R.drawable.priority_high);

    private int drawableResource;

    Priority(int drawableResource) {
        this.drawableResource = drawableResource;
    }

    public int getDrawableResource() {
        return drawableResource;
    }
}

这就是我创建一些示例待办事项的方式:

private TodoItemDao() {
    todoItems.add(new TodoItem("pet shop", new Date(), "buy a nice zombie pig", Priority.HIGH));
    todoItems.add(new TodoItem("barber", new Date(), "cut lion's hair", Priority.MEDIUM));
    todoItems.add(new TodoItem("mine", new Date(), "we need redstones", Priority.LOW));
}

那么在这个场景中,如何将todo优先级翻译成不同的语言呢?我通常这样做

    titleEditText = (EditText) findViewById(R.id.et_title);

...但不知道如何在枚举中执行此操作以及如何在项目创建时设置优先级。有什么想法吗?

编辑:

恐怕我还不够清楚。使用此行:

titleEditText = (EditText) findViewById(R.id.et_title);

我想表明我已经在使用 strings.xml。我只是不知道如何将它与枚举一起使用。

不要直接从枚举中进行。照常将翻译放入 strings.xml 文件。编写一个函数 int mapToStringResource(Priority) 将 Priority 转换为正确的 id。调用setText(mapToStringResource(priority))设置文本。

如前所述,使用 strings.xml 并添加翻译。无论你有多少种语言,都可以这样做。

建议您将以下内容添加到您的枚举或您可以访问它的其他地方:

public String getPriorityName(Priority ref, Context c){
    switch(ref){
        case Priority.LOW:
            return c.getString(R.string.priorityLowDescription);
            break;

        (Showing only one here, but you can see the pattern)
    }
}

这会考虑您的优先级实例,并基于此 returns 来自 strings.xml 的适当字符串。这意味着它将以您的设备设置的语言获取字符串(或用户手动设置,具体取决于设置)

我最终通过扩展添加了一个函数到我的枚举 Document.DocType(因为生成了枚举代码 - 否则我会直接添加它)像这样:

fun Document.DocType.mapToStringResource() : Int {
when (this) {
    Document.DocType.PDF -> return R.string.documents_docType_PDF
    else -> {
        return 0
    }
}

(注意:如果资源不存在,返回 0 会崩溃。也许最好将其设为可选或为“未找到”设置默认字符串资源)

然后像这样在 Jetpack Compose 中使用它:

Text(text = stringResource(document.docType.mapToStringResource()))