Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do we know when an Activity's views have been layed out

I have an Activity with a view hierarchy as follows:

<RelativeLayout>
    <LinearLayout>
        <GridLayout />
    </LinearLayout>
</RelativeLayout>

The top RelativeLayout takes up the full screen while the LinearLayout takes up a subset of the screen. I'm trying to set the size of the children views of the GridLayout in such a way that with n rows and m columns the size of cells is directly related to the n,m values and the width and height of the LinearLayout.

So for example, I'm trying to get the cell width and height as follows:

int linearLayoutWidth = mLinearLayout.getMeasuredWidth();
int linearLayoutHeight = mLinearLayout.getMeasuredHeight();
...

int rows = mGridModel.getRows() + 1;
int columns = mGridModel.getColumns() + 1;
int cellWidth = (int) (linearLayoutWidth / columns);
int cellHeight = (int) (linearLayoutHeight / rows);

Unfortunately, mLinearLayout.getMeasuredWidth() does not return the correct size when the view is created. It always returns the actual device's screen width until the views have been fully laid out - in which case it is too late. I have already given my children cell views the size based on the initially completely incorrect values.

My question is - how do I know when the views have been FULLY laid out. I need to query for their correct or actual measured width/height.

setContentView() creates the views and theoretically lays them out. But they views are not guaranteed to be in their final correct locations/sizes yet.

like image 727
mdupls Avatar asked Dec 13 '22 03:12

mdupls


1 Answers

You can add ViewObserver to any view, in this observer there is a callback method onGlobalLayout, invoked when Layout has been laid;

ViewTreeObserver observer = view.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        //in here, place the code that requires you to know the dimensions.


         //this will be called as the layout is finished, prior to displaying.
    }
}
like image 78
jeet Avatar answered Feb 23 '23 19:02

jeet