我目前正在開發android 測驗應用程序,我實現了「重置」按鈕,可以重置問題並隨機化它們,但是我' m在調用MainActivity.java中的.xml文件中的隨機字符串時遇到了麻煩。Java/Xml/Android - 從Java中調用隨機字符串String文件
我都在像這樣的strings.xml文件中列出了我的問題,以使它們易於翻譯:
<string name="q1">The reactor at the site of the Chernobyl nuclear disaster is now in which country?</string>
<string name="a1">A. Slovakia</string>
<string name="b1">B. Ukraine</string>
<string name="c1">C. Hungary</string>
<string name="d1">D. Russia</string>
<string name="q1answer">B</string>
所有的問題在該文件中列出像Q1, q2,q3,和ABCD答案相同:a1,b1,c1,d1; a2,b2,c2,d2等。
有很多問題,但按鈕只選擇其中5個並將它們顯示在屏幕上。該問題是,我只是不能訪問字符串,如果我想使用隨機生成一個整數可能發現它們的.xml:
for (int i = 1; i <= 5; i++) {
// I managed to get the identifier of the TextView with the for loop like that (TextViews for questios are listed q1q, q2q, q3q, q4q, q5q):
// I would like to do the same thing down there with Strings.
TextView question = (TextView) findViewById(getResources().getIdentifier("q" + i + "q", "id", this.getPackageName()));
// randomQuestion is the number of the question in random number generator from different method.
randomQuestion = randomizeNumbers();
// And here I'm stuck, this will show "q1-randomNumber" instead of the real question,
// because it does not see it as an ID. I tried various different solutions, but nothing works.
question.setText("q" + randomQuestion);
// I left the most silly approach to show what I mean.
}
我能做些什麼,以使計算機區分名的字符串?所以它顯示的是真正的問題而不是「q1」「q6」「q17」?
感謝您提前幫忙!
可悲的是我被告知使用的.xml所以它是翻譯之後輕鬆,但第一個回覆解決問題 :)。 (); getIdentifier(「q」+ randomQuestion,「string」,this.getPackageName()); 完美的作品,早些時候我沒有將「id」改爲「string」。謝了哥們! – Qlak
很高興幫助!試圖給一點額外的東西:如果解決了問題,D可以自由地「回答」答案。祝你好運 ! –