为什么则getIdentifier始终为0返回一个字符串 [英] Why getIdentifier is returning always 0 for a string

查看:342
本文介绍了为什么则getIdentifier始终为0返回一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想动态改变文本和活动MAIN1哪个扩展到文本1,其中标题和textes,我这样做是code,但从来没有工作过的标题:

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

问题在于stringId1和stringId2赋予0的值。

the problem is that stringId1 and stringId2 giving 0 value.

推荐答案

按照要求在评论,具有的 地图

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
}

您也可能想要把 theMap 文本和揭露一些的getTitle(INT )的getText(INT)方法使用Android的资源mecanism

You might also want to put theMap in Text and expose some getTitle(int) and getText(int) method or use android resources mecanism

另外,如果可以的话,我会建议阅读本Java教程

Also if I may, I would advise reading this java tutorial

这篇关于为什么则getIdentifier始终为0返回一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆