androidandroid-linearlayoutandroid-tablelayoutfileoutputstreamandroid-viewtreeobserver

Create a PDF after linear layout is done drawing


I am trying to create a PDF of a nested linear layout with a table layout. My problem is that my initial attempts led to a file being drawn without the complete view.

To get around this I decided to only write to the file after the view is done loading and I tried to listen for the event using the ViewTreeObserver.globalOnLayoutListener but it never got evoked. So I decided to use View.post() and it too doesn't seem to work. I have waited 4 minutes thinking it may take a while to draw since the layout file is large but the listener, and later on the runnable were never called. I verified the facts using both breakpoints, and logcat.

Where am I going wrong?


Solution

  • So I figured it out, it is not that I was calling the draw before my layout was done rendering, I was just trying to draw on an A4 PostScript pt sized page using an xxhdpi screen that had too many pixels to fit into the dimensions. To get around this I used px values instead of dps for my view dimensions, and I also set the layout size to be the same size as the page to ensure the content had a perfect fit.

    I managed to change the view dimensions of the layout by calling measure(width, height) to force the view to remeasure the sizes of itself and its children constrained by the provided dimensions, and then layout(left, top, right, bottom) to force it to render itself and its children within a boundary created by the passed coordinates.

    The best thing is that both measure and layout are synchronous so you are guaranteed that the view is ready before you try to do anything with it.