20

Is there a dynamic way to get at the root layout (the one that is the parent to all the other Layouts) in the XML currently set to my Activity?

What I'm after is rather than giving my root layout an explicit id and finding it via findViewById, I'm hoping to get something along the lines of

pseudo code:

this.findTopLayout();

having already called setContentView(R.layout.foo);

I'm not seeing anything in the spec that would do the trick, am I just missing it, or is there no way to do this?

Yevgeny Simkin
  • 26,055
  • 37
  • 127
  • 228
  • 1
    Is this what you're looking for? http://stackoverflow.com/questions/4486034/get-root-view-from-current-activity – DeeV Jan 12 '13 at 03:25
  • it would appear that that's exactly what I'm looking for... you should post it as an answer, and I'll give you the green checkmark (and thanks very much) – Yevgeny Simkin Jan 12 '13 at 03:27

2 Answers2

60

You try out this way to get the root layout:

getWindow().getDecorView().findViewById(android.R.id.content);

OR

getWindow().getDecorView().getRootView();

GrIsHu
  • 28,433
  • 10
  • 61
  • 99
4

Note that apart from the method described by Grishu, you can also use the method getParent on any view (this includes buttons, imageviews, layouts, etc) to get the parent of that view (the parent returned might also have a parent). Hence, an alternative method would be to loop on getParent from a particular view until getParent returns null. At that point, you would have found the root view of your content view.

Dhruv Gairola
  • 8,807
  • 5
  • 37
  • 41
  • yeah, that's useful in the other direction, but I am hoping (and the comments appear to give that exact answer) to avoid knowing anything about the layout specifically and to just walk my way down into it from the top. – Yevgeny Simkin Jan 12 '13 at 03:39
  • you don't need to know anything about the layout or view even when calling getParent. – Dhruv Gairola Jan 12 '13 at 03:43
  • no, but I'd need to know the id of the child to get at IT first, right? Or am I missing something? – Yevgeny Simkin Jan 12 '13 at 03:49
  • i see your point- yes, you would need to have the child object in order to call getParent on it. – Dhruv Gairola Jan 12 '13 at 03:54