2016-09-01 106 views
1

是否有任何方法以編程方式更改R.string?因爲它拋出了一個錯誤。以編程方式更改資源getString()

基本上我想這樣做: String parkAdd = getString(R.string.stg_ParkAddress_+id);

因爲我硬編碼被改變,根據ID字符串。

我試圖這樣做,但不工作:

String parkAdd = getString(R.string.stg_ParkAddress_1); 
     parkAdd = parkAdd.replace("1",id); 
     if (!parkAdd.equalsIgnoreCase("")){ 
      tvParkAddress.setText(parkAdd); 
     } 

謝謝。

+0

您無法更改資源值programmaticaly。基本上你不能在運行時更改 –

+0

@AmanGrover,但我需要一個解決方案來獲得這個,我需要做一個開關? – FilipeOS

+0

但是在運行時不可能更改任何資源值。 –

回答

5

R.string.xxx實際上是一個常量,並且該值不能附加到該資源,永遠不會找到該資源。您可以搜索R.java看到你的應用程序中的值:

public static final class string { 
    public static final int about_open_source_heading=0x7f060013; 
    public static final int about_open_source_list=0x7f060014; 
} 

如果你硬編碼依賴於特定的字串值,也許你可以做這樣的事情:

switch (id) { 
    case 12345: 
     parkAddr = R.string.stg_ParkAddress_12345; 
     break; 
    case 12346: 
     parkAddr = R.string.stg_ParkAddress_12346; 
     break; 
} 
+0

Gary Bak,你爲什麼要訪問'public static final class string'? – FilipeOS

+0

@FilipeOS - 這只是'R.java'文件的一個樣例。當你使用常量R.string.stg_ParkAddress_X時,你引用該文件/類中的最後一個。 –

0

只需使用id

String parkAdd = getString(R.string.stg_ParkAddress) + id; 
+0

不,因爲它會獲取我的字符串而不是stg_ParkAddress_X – FilipeOS

1

這是不可能以編程方式編輯字符串資源,做另一個類,讓你的琴絃在運行時放置在這個類和訪問串連它。

2

字符串資源不能在運行時更改。您可以將字符串保存到SharedPreference中,您可以修改並保存以供進一步使用。

相關問題