16

is there a way to get every view that is inside my activity? I have over 200 views including buttons, and images, so i want to be able to access them by using a loop

for example something like

for (View v : this)
{
     //do something with the views 
     //depending on the types (button, image , etc)
}
M.Sameer
  • 3,072
  • 1
  • 24
  • 37
aryaxt
  • 76,198
  • 92
  • 293
  • 442

5 Answers5

30

is there a way to get every view that is inside my activity?

Get your root View, cast it to a ViewGroup, call getChildCount() and getChildAt(), and recurse as needed.

I have over 200 views including buttons, and images, so i want to be able to access them by using a loop

That is a rather large number of Views.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • 1
    thanks a lot , perfect an invisible object (button) was blocking my whole screen, I used this to find out what item was blocking and found it :) – aryaxt Jul 11 '10 at 00:12
  • 7
    The `hierarchyviewer` tool that comes with the SDK can help you find issues like this. It can display your app's view hierarchy visually as a tree, allowing you to inspect the properties of each view. – adamp Jul 11 '10 at 02:26
  • 1
    I know but most of the objects are added to the screen through code. – aryaxt Jul 14 '10 at 17:22
11

To be specific:

private void show_children(View v) {
    ViewGroup viewgroup=(ViewGroup)v;
    for (int i=0;i<viewgroup.getChildCount();i++) {
        View v1=viewgroup.getChildAt(i);
        if (v1 instanceof ViewGroup) show_children(v1);
        Log.d("APPNAME",v1.toString());
    }
}

And then use the function somewhere:

show_children(getWindow().getDecorView());

to show all Views in the current Activity.

Martin B
  • 337
  • 4
  • 9
2

Try to find all view associated with the Activity.

give the following command.

ViewGroup viewgroup=(ViewGroup)view.getParent();
viewgroup.getchildcount();

iterate through the loop.

We will get the Result.

Jabeer
  • 21
  • 1
1

Nice way to do this in Kotlin recursivelly:

private fun View.getAllViews(): List<View> {
    if (this !is ViewGroup || childCount == 0) return listOf(this)

    return children
            .toList()
            .flatMap { it.getAllViews() }
            .plus(this as View)
}
Stanislav Kinzl
  • 370
  • 4
  • 6
0

You can use the hierarchyviewer, It allows you to see the view hierarchy including those created in code. It's primary reason is for debugging things like this. The latest Android Studio now has this feature in the Device Monitor that lets you make a dump of the UI to debug it.