2011-08-30 55 views
2

正如标题所说,我的问题是我不知道如何/如何在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...'). 
+0

这个问题是真的[此的其他问题(的副本http://stackoverflow.com/questions/3722374/android-how-to-inject-a-string-元素到另一个字符串元素在xml),并且它接受的答案似乎是th最好的方法。感谢@Brian指出这一点, – cybersam

回答

2

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

进一步了解详细:http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling

+0

但是使用String.format并在运行时组合Stings我有问题,我想在帮助文本中使用它。但是,如果我想要写'要使用函数“@ sting/a_function”,您需要...'我必须创建2个项目'“要使用函数'和'你需要......'并将它们与'@ sting/a_function'的内容组合在一起。如果我错了,请纠正我! – hnzlmnn

+0

一个字符串,例如:'要使用函数%1 $ s,您需要...'并使用'String.format'指定函数的名称。 –

2

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

+0

感谢您的快速回答。希望这样的功能很快就会加入! – hnzlmnn

1

编辑:其实this solution, using custom ENTITY entries是好得多。


下应该工作开箱:

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

我只是API级别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; 
} 
0

一个很好的方式插入经常使用的字符串(如应用程序名称)不使用Java代码here XML:

<?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> 
相关问题