2011-08-30 58 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> 
相關問題