tags:

views:

137

answers:

2

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

Something like:

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

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

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

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}

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.

EDIT:

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

You can use reflection on an inner class, but the syntax is packagename.R$id. Note that reflection can be very slow and you should REALLY avoid using it.

Romain Guy
I was thinking that reflection might be too expensive, and not worth it just for the convenience of not having to hand-code some items. I was hoping that there was some built-in, non-relfection-based way of accessing these ids since it seems like a common enough scenario. Thanks, at least, for the syntax on reflecting on inner classes. It's useful to know.
John Tabs
A: 

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

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.

Qberticus
This seems to be the ticket! Glad the clarification helped. It hadn't crossed my mind to access the children views of my layout. Thanks a bunch for the insight.
John Tabs