访问以名称在一个循环变量 [英] Access variables by name in a loop

查看:101
本文介绍了访问以名称在一个循环变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个Android项目,我有很多可绘制的。这些可绘制都被命名为喜欢 icon_0.png icon_1.png ... icon_100。 PNG 。我想补充的所有资源的ID,这些可绘制到整数的ArrayList。 (对于那些,谁不知道Android的,只有Java的,我说的是静态变量,在静态内部类一类的,如 R.drawable.icon_0 。所有此静态变量是整数。)

I'm working on an Android project, and i have a lot of drawables. These drawables are all named like icon_0.png, icon_1.png ... icon_100.png. I want to add all the resource id's of these drawables to an ArrayList of Integers. (For those, who do not know android, only Java, i am talking about static variables, in a static inner class of a class, like R.drawable.icon_0. All of this static variables are Integers.)

有没有更有效的方式来做到这一点,不是一个逐一添加?像

Is there a more efficient way to do this, than adding them one by one? Like

ArrayList<Integer> list = new ArrayList<Integer>();
list.add(R.drawable.icon_1);
list.add(R.drawable.icon_2);
...
list.add(R.drawable.icon_100);

通过他们,我不知怎么循环?像

Can i loop through them somehow? Like

for(int i=0; i<100; i++)
{
    list.add(R.drawable.icon_+i);  //<--- I know this doesn't work.
}

我在哪里这些静态整数是该文件无法控制,我不能在运行时创建的可绘制。

I have no control over the file where these static integers are, and i cannot create the drawables in runtime.

任何帮助将是AP preciated!

Any help would be appreciated!

修改

好吧,我读的答案,但我有一个重大问题:我没有访问任何上下文情况下,我需要创建这个数组/列表IDS(我做一个静态initialzer块),所以getResources()方法中,哪两个问题的答案的建议不会工作。是否有这样做的任何其他方式?

Okay, i read the answers, but i have one major problem: I don't have access to any Context instances where i need to create this array/list of ids (i do it in a static initialzer block), so the getResources() method, what two of the answers suggested wont work. Is there any other way of doing this?

推荐答案

一种方法是使用反射API。

One way would be to use reflection API.

沿线的东西...

Field[] fields =  R.drawable.class.getFields();
List<String> names = new ArrayList<String>(); 
for (Field field : fields) {
    if(field.getName().startsWith("icon")) 
       names.add(field.getName());    
}

int resid = getResources().getIdentifier(names.get(0), "drawable", "com.org.bla");

我没有测试过这一点,但你的想法。

I haven't tested this, but you get the idea.

这篇关于访问以名称在一个循环变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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