繁体   English   中英

我可以在 string.xml 的字符串资源中使用字符串资源吗?

[英]Can I use a String Resource in a String Resource in string.xml?

正如标题所说,我的问题是我不知道是否/如何在 string.xml 的字符串资源中使用字符串资源。

<string name="projectname">Include Test</string>
<string name="about">@string/projectname is to test if you can use a String Resource in a String Resource</string>

我的问题是是否有人知道我是否可以写

<string name="identifier">@string/other_identifier</string>

因为 Eclispe 说

error: Error: No resource found that matches the given name (at 'other_identifier' with value '@string/other_identifier eingeben...').

不,我不认为这是可能的。

您最好在运行时构造这些String String.format的帮助下将不同的String资源组合在一起。

更多细节:http: //developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling

编辑:实际上这个解决方案,使用自定义ENTITY条目要好得多。


以下应该是开箱即用的:

<string name="identifier">@string/other_identifier</string>

我刚刚用 API Level 8 试了一下,效果很好。 另请参阅https://stackoverflow.com/a/6378421/786434

换句话说,为了能够交叉引用字符串,您可以为自己创建一个小的帮助方法:

private static Pattern pattern = Pattern.compile("@string/(\\S+)");

public static String getString(Resources res, int stringID) {
String s = res.getString(stringID);

Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
    try {
    final Field f = R.string.class.getDeclaredField(matcher.group(1));
    final int id = f.getInt(null);
    final String replace = res.getString(id);
    s = s.replaceAll(matcher.group(), replace);

    } catch (SecurityException ignore) {
    } catch (NoSuchFieldException ignore) {
    } catch (IllegalArgumentException ignore) {
    } catch (IllegalAccessException ignore) {
    }
}

return s;
}

一种在 xml 中插入常用字符串(例如应用程序名称)的好方法,而无需在此处使用 Java 代码:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE resources [
<!ENTITY appname "MyAppName">
<!ENTITY author "MrGreen">
]>

<resources>
    <string name="app_name">&appname;</string>
    <string name="description">The &appname; app was created by &author;</string>
</resources>

是的,你可以 :) 虽然不是原生的,但你可以使用这个小型库,它允许你在构建时解析这些占位符,因此你不必添加任何 Java/Kotlin 代码来使其工作。

根据您的示例,您必须像这样设置字符串:

<string name="projectname">Include Test</string>
<string name="about">${projectname} is to test if you can use a String Resource in a String Resource</string>

然后插件将负责创建以下内容:

<!-- Auto generated during compilation -->
<string name="about">Include Test is to test if you can use a String Resource in a String Resource</string>

更多信息在这里: https ://github.com/LikeTheSalad/android-stem

免责声明:我是该库的作者。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM