【问题标题】:Are "compound identifiers" possible for string resources in Android? [duplicate]Android中的字符串资源是否可以使用“复合标识符”? [复制]
【发布时间】:2020-09-15 06:15:02
【问题描述】:

字符串资源是否可以使用“复合标识符”? 像这样

val level = 1      <- current level
getString(R.string.answer + level)    <- and this is get (R.string.answer1) string

这样的事情可能吗?

【问题讨论】:

    标签: android string


    【解决方案1】:

    利用Resources.getIdentifier(String, String, String)方法动态生成你想要的资源ID,然后使用生成的ID照常调用getString(int)

    例如

    int level = 1;
    String name = "answer" + level;
    int stringResId = getResources().getIdentifier(name, "string", getPackageName());
    
    String result = getString(stringResId);
    

    有关参数的 Javadoc 信息,请参阅链接。


    查看相关副本了解更多详情,包括 Kotlin 示例:

    【讨论】:

    • 无法使用字符串数组。代码 -> link string.xml -> link
    • @player1ykt 您的问题没有指定字符串数组,请查看新添加的最后一个链接,该链接似乎可以很好地解决问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-02
    • 2017-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-13
    • 2012-06-09
    相关资源
    最近更新 更多