为什么getIdentifier对于字符串总是返回0

时间:2015-02-07 10:40:49

标签: android superclass

我正在尝试动态更改活动Main1的文本和标题,扩展到Text1标题和文本,我做了这段代码,但从未工作过:

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));

问题是stringId1和stringId2给出0值。

1 个答案:

答案 0 :(得分:0)

根据评论中的要求,使用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
}

您可能还想将theMap放入Text并公开一些getTitle(int)getText(int)方法使用android resources mecanism


如果可以的话,我建议你阅读this java tutorial