问题
I'm trying to dynamically change the text and the title of an Activity Main1 which extended to Text1 where the titles and textes, I did this code but never worked:
public class MainText1 extends Text {
String
tx1=text1,tx2=text2,tx3=text3,
tl1=title1, tl2=title2,tl3=title3,tl,tx;
num = Integer.parseInt(getIntent().getStringExtra("somekey1")); // this data is coming from the menu, it depends on which button is clicked
tl="tl"+num;
tx="tx"+num;
stringId1 = getApplicationContext().getResources().getIdentifier(tl, "string", getPackageName());
stringId2 = getApplicationContext().getResources().getIdentifier(tx, "string", getPackageName());
if (stringId1 > 0) {
title=getApplicationContext().getResources().getString(stringId1);
text2=getApplicationContext().getResources().getString(stringId2);
}
else
{
title=Integer.toString(stringId1);
text2=Integer.toString(stringId2);
}
text1 = "<font color=#000080><b>" + title + "</b></font>";
t1.setText(Html.fromHtml(text1));
t2.setText(Html.fromHtml(text2));
the problem is that stringId1 and stringId2 giving 0 value.
回答1:
As requested in the comments, with a Map:
Map<String, String> theMap = new HashMap<String, String>();
theMap.put("tx1", text1);
theMap.put("tx2", text2);
theMap.put("tx3", text3);
theMap.put("tl1", title1);
theMap.put("tl2", title2);
theMap.put("tl3", title3);
num = Integer.parseInt(getIntent().getStringExtra("somekey1")); // this data is coming from the menu, it depends on which button is clicked
tl="tl"+num;
tx="tx"+num;
if (theMap.containsKey("tl") {
title = theMap.get("tl");
} else {
// do something
}
if (theMap.containsKey("tx") {
text2 = theMap.get("tx");
} else {
// do something
}
You might also want to put theMap in Text and expose some getTitle(int) and getText(int) method or use android resources mecanism
Also if I may, I would advise reading this java tutorial
来源:https://stackoverflow.com/questions/28381146/why-getidentifier-is-returning-always-0-for-a-string