2015-02-07 173 views
0

我想動態改變文本和活動MAIN1其擴展到文本1在標題和textes,我做了這個代碼,但從來沒有標題的工作:爲什麼則getIdentifier始終爲0返回一個字符串

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值。

+0

大概是因爲資源不存在.. – 2015-02-07 10:43:09

+0

沒有它確實存在,這是超類代碼:'公共類文本擴展活動{ \t \t \t \t公共字符串 \t titl1 =「KAR」 \t tex1 = 「GGGGG」, \t titl2 = 「2222」, \t TEX2 = 「KAR2」, \t \t = titl3 「333」, \t tex3 = 「kar3」;}' – AndroDev 2015-02-07 10:51:44

+0

這裏可能有些混亂,你應該閱讀[關於資源的文檔](http://developer.android.com/guide/topics/resources/index.html) – 2015-02-07 10:51:52

回答

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 
} 

您可能還希望把theMapText和揭露一些getTitle(int)getText(int)方法採用Android resources mecanism


另外如果我可以,我會建議閱讀this java tutorial

相關問題