Android:以编程方式迭代资源ID

时间:2010-08-23 06:36:15

标签: android

我希望能够遍历生成的R文件中的所有字段。

类似的东西:

for(int id : R.id.getAllFields()){
//Do something with id, like create a view for each image
}

我尝试过反射,但我似乎无法加载R类中包含的特定内部类。所以,例如,这对我不起作用:

Class c = Class.forName("packageName.R.id")

我可以反思R类本身,但我需要id类中的字段。

我也尝试过查看Resources类,但在那里找不到任何东西。在这种情况下,似乎您可以获取resourceID并获取该id的字符串名称,或者获取字符串名称并获取相应的resourceID。我找不到类似的东西:

int[] Resources.getAllResourceIDs()

也许我正在犯这个错误。或者也许我不应该手动打字,例如:

int[] myIds = {R.id.firstResource, R.id.secondResource}

这种方法的缺点是在使用UI设计器时不够灵活。每当他向XML文件添加新资源时,我都必须更新代码。显然不是太痛苦,但它仍然是好的,似乎它应该是可行的。

编辑:

以下关于ViewGroup.getChildCount()/ ViewGroup.getChildAt()的答案正常。但是,我还必须找到一种方法来实例化我的XML ViewGroup / Layout。要做到这一点,尝试类似:

LayoutInflater li = MyActivity.getLayoutInflater();
ViewGroup vg = (ViewGroup) li.inflate(R.layout.main, null);

3 个答案:

答案 0 :(得分:6)

我发现“Class.forName(getPackageName()+”。R $ string“);”可以让你访问字符串资源,也应该适用于id,drawable,exc。

然后我使用这样的类:


import java.lang.reflect.Field;

import android.util.Log;

public class ResourceUtil {

    /**
     * Finds the resource ID for the current application's resources.
     * @param Rclass Resource class to find resource in. 
     * Example: R.string.class, R.layout.class, R.drawable.class
     * @param name Name of the resource to search for.
     * @return The id of the resource or -1 if not found.
     */
    public static int getResourceByName(Class<?> Rclass, String name) {
        int id = -1;
        try {
            if (Rclass != null) {
                final Field field = Rclass.getField(name);
                if (field != null)
                    id = field.getInt(null);
            }
        } catch (final Exception e) {
            Log.e("GET_RESOURCE_BY_NAME: ", e.toString());
            e.printStackTrace();
        }
        return id;
    }
}

答案 1 :(得分:5)

您对我评论的回复有助于我更好地了解您的目标。

您可以使用ViewGroup#getChildAtViewGroup#getChildCount遍历视图层次结构中的各种ViewGroup,并对返回的instanceof执行View检查。然后,您可以执行任何操作,具体取决于子视图的类型以及它们在层次结构中的位置。

答案 2 :(得分:2)

您可以对内部类使用反射,但语法为packagename.R $ id。请注意,反射可能非常慢,您应该真的避免使用它。