How to retrieve the dimensions of a view?

前端 未结 16 1662
小蘑菇
小蘑菇 2020-11-22 01:09

I have a view made up of TableLayout, TableRow and TextView. I want it to look like a grid. I need to get the height and width of this grid. The methods

16条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 01:37

    You are trying to get width and height of an elements, that weren't drawn yet.

    If you use debug and stop at some point, you'll see, that your device screen is still empty, that's because your elements weren't drawn yet, so you can't get width and height of something, that doesn't yet exist.

    And, I might be wrong, but setWidth() is not always respected, Layout lays out it's children and decides how to measure them (calling child.measure()), so If you set setWidth(), you are not guaranteed to get this width after element will be drawn.

    What you need, is to use getMeasuredWidth() (the most recent measure of your View) somewhere after the view was actually drawn.

    Look into Activity lifecycle for finding the best moment.

    http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

    I believe a good practice is to use OnGlobalLayoutListener like this:

    yourView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (!mMeasured) {
                    // Here your view is already layed out and measured for the first time
                    mMeasured = true; // Some optional flag to mark, that we already got the sizes
                }
            }
        });
    

    You can place this code directly in onCreate(), and it will be invoked when views will be laid out.

提交回复
热议问题