Android:以编程方式遍历资源ID [英] Android: Programmatically iterate through Resource ids

查看:115
本文介绍了Android:以编程方式遍历资源ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to be able to iterate through all of the fields in the generated R file.

类似的东西:

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

我尝试了反射,但是我似乎无法加载R类中包含的特定内部类.因此,例如,这对我不起作用:

I've tried reflection, but I can't seem to load a specific inner class that's contained inside the R class. So, for example, this wouldn't work for me:

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

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

I can reflect on the R class itself, but I need the fields within the id class.

我也尝试浏览Resources类,但是在那里找不到任何东西.在这种情况下,您似乎可以采用resourceID并获取该ID的字符串名称,也可以采用字符串名称并获取相应的resourceID.我找不到类似的东西:

I also tried looking through the Resources class, but couldn't find anything there. In that case, it seems you can take a resourceID and get the string name of that id, or take a string name and get the corresponding resourceID. I couldn't find anything like:

int[] Resources.getAllResourceIDs()

也许我正在解决这个错误.或者,也许我不应该反对手动输入所有内容,例如:

Maybe I'm going about this wrong. Or maybe I shouldn't fight typing them all in by hand, e.g.:

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

这种方法的缺点是与我的UI设计器一起使用时不够灵活.每当他将新资源添加到XML文件时,我都必须更新代码.显然不是很痛苦,但是拥有它仍然会很好,而且似乎应该可行.

This approach has the downside of not being as flexible when working with my UI designer. Whenever he adds a new resource to the XML file, I'll have to update the code. Obviously not too painful, but it would still be nice to have and it seems like it should be doable.

下面关于ViewGroup.getChildCount()/ViewGroup.getChildAt()的答案很好.但是,我还必须找到一种实例化XML ViewGroup/Layout的方法.为此,请尝试以下操作:

The answer below about ViewGroup.getChildCount()/ViewGroup.getChildAt() works fine. But, I also had to find a way to instantiate my XML ViewGroup/Layout. To do that, try something like:

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

推荐答案

您对我的评论的答复有助于我更好地了解您要做什么.

Your reply to my comment helped me get a better idea of what you're trying to do.

您可能可以使用 ViewGroup#getChildAt ViewGroup#getChildCount 进行循环遍历视图层次结构中的各个ViewGroup,并对返回的View执行instanceof检查.然后,根据子视图的类型以及它们在层次结构中的位置,您可以执行任何所需的操作.

You can probably use ViewGroup#getChildAt and ViewGroup#getChildCount to loop through various ViewGroups in your view hierarchy and perform instanceof checks on the returned Views. Then you can do whatever you want depending on the type of the child views and where they are in your hierarchy.

这篇关于Android:以编程方式遍历资源ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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