2016-10-04 78 views
0

一个字符串数组我收到字符串数组的名字从我的意图演员(KI1,KI2等)建设资源位置在android系统

而不是硬编码字符串数组名称(如R.array.KI1),我希望变量替换它们。

strdata = receiverIntent.getExtras().getString("intentExtra"); 
String[] pointDetails = getResources().getStringArray**(R.array.KI1);** 

资源文件

<resources> 
    <string-array name="KI1"> 
     <item>Categories Text KI1</item> 
     <item>Unitary Channel Text KI1</item> 
     <item>Localization Text KI1</item> 
     <item>Action Text KI1</item> 
     <item>Indication Text KI1</item> 
     <item>Point location Text KI1</item> 
     <item>KI1.png</item> 
    </string-array> 

    <string-array name="KI2"> 
     <item>Categories Text KI2</item> 
     <item>Unitary Channel Text KI2</item> 
     <item>Localization Text KI2</item> 
     <item>Action Text KI2</item> 
     <item>Indication Text KI2</item> 
     <item>Point location Text KI2</item> 
     <item>KI2.png</item> 
    </string-array> 
</resources> 

为什么不可能做这样的事情:

String[] pointDetails = getResources().getStringArray("R.array." + strdata); 

我想要一个变量的输出是这样的:R.array.strdata

回答

0

因为getStringArray();接受int值,但你传递字符串给它。

你为什么不使用开关的情况下,或者如果进出口...像

String[] pointDetails ; 

    switch(strdata) 
    { 
    case "KI1": 
     pointDetails = getResources().getStringArray(R.array.KI1); 
    break; 
    case "KI2": 
     pointDetails = getResources().getStringArray(R.array.KI2); 
    break; 
} 
+0

如果有KI400,我会写400案件,但如果我能知道如何用一个变量替换这将是2行代码。 – woeiwkq

+0

为了实现你想要的,你需要通过名称而不是id来获取资源。这是如何: 'Resources res = getResources(); int id = res.getIdentifier(strdata,“array”,getContext()。getPackageName()); String [] pointDetails = res.getStringArray(id);' – George

+0

感谢@Giorgos,您的解决方案能够运作:) – woeiwkq