Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

android - Why getIdentifier is returning always 0 for a string

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...