2012-05-07 42 views
2

好的我沒有做很好的工作來解釋我的問題,所以在這裏修改了幾次。使用字符串加載預設腳本

我有一個調查,調查產生一個整數。我把這個數字轉換成一個字符串文件名,它與存儲在我的資源中的預設字符串有關。根據對問題的選擇,最後需要不同的字符串。

此代碼生成所需的命令行; R.string.C####

int Q1 = question1.getmCounter(); 
int Q2 = question2.getmCounter(); 
int Q3 = question3.getmCounter(); 
int Q4 = question4.getmCounter(); 

int qTotal = Q1 + Q2 + Q3 + Q4; 
String Test5 = "R.string.c" + qTotal; 

而這段代碼是在onCreate中爲TextView生成內容的。

 textOut = (TextView) findViewById(R.id.ChmpNametxt); 
    textOut.setText(Test5); 

現在我的想法是它將讀取Test5作爲「R.string.C####」並加載所需的字符串。它不這樣做,我想知道如何將Test5的內容放入命令行。

希望someon能幫助我的IM啤酒..

由於提前

克里斯

回答

1

你得到正確的答案已經在這裏:Creating Strings than can be used as Filepath - Eclipse/Android

你的情況:

String stringId = "c" + qTotal; //note: not the same as what you did with your Test5 
int resId = getResources().getIdentifier(stringId, "string", getPackageName()); 
textOut.setText(resId); 

或者,我們misunderstandig你的單詞 「命令行」 的使用?

+0

啊哈我看看發生了什麼現在..它不喜歡getPackageName,但是我需要在那裏聲明一些東西嗎? –

+0

啊不使用getClass(),刪除那部分,更新了答案 –

+0

啊這些評論需要更新生活.. xD –

0

你需要得到reosurce ID爲您的文本,該代碼獲取資源ID爲您提供:

ContextWrapper cw = this.getContext();// how you get this can be different, but you need a ContextWrapper from somewhere to use. 
int resId = cw.getResources().getIdentifier("c" + qTotal, "string", cw.getPackageName()); 

然後,您可以使用textOut.setText和resId變量作爲參數。

+0

'Test5'格式不正確。看到我的答案。 –

+0

也沒有在你編輯後,看起來你粘貼了我的第一個版本的代碼,忘記了C :) :) –

+0

@Pulsar是的,當我看到你的答案時才意識到。編輯。 –