3

For testing purposes, I need to get the coordinates of all visible views on the screen. However, when checking the output, it seems the UI Thread is not done drawing/positioning/applying settings to all the views yet. Some views are 0x0 pixels while they should be (and they are on both the emulator and a physical device) visible. Some bottom aligned buttons are positioned like stairs, et cetera.

Q: how can i wait for the UI Thread to complete drawing (or at least wait for like a second, that should be more than enough), so the coordinates of all visible views are accurate?

I suspects it's something with Threads, but I couldn't find any definitive answers. As of yet, I do not have any self-declared threads.

Edit: I use onBackPressed to make a bunch of views visible, then capture that in xml, make the previous views invisible and other views visible, capture that in xml, etc. I iterate trough a few different combinations of views and "xml-screenshot" each combination.

stealthjong
  • 10,858
  • 13
  • 45
  • 84
  • Maybe posting a runnable to the UI thread works here too: http://stackoverflow.com/a/9425410/995891 – zapl Sep 26 '12 at 09:51

1 Answers1

6
LinearLayout layout = (LinearLayout)findViewById(R.id.YOUD VIEW ID);
ViewTreeObserver vto = layout.getViewTreeObserver(); 
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
    @Override 
    public void onGlobalLayout() { 
        this.layout.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
        int width  = layout.getMeasuredWidth();
        int height = layout.getMeasuredHeight(); 

    } 
});

You'll need to adjust this to work with your layout, and add an ID to the basic parent layout.

By using a ViewTreeObserver, you can get to know when your layout has finished drawing, and run your required code then

Raghav Sood
  • 81,899
  • 22
  • 187
  • 195