我们何时知道活动的视图何时布置 [英] When do we know when an Activity's views have been layed out

查看:57
本文介绍了我们何时知道活动的视图何时布置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个活动,其视图层次如下:

I have an Activity with a view hierarchy as follows:

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

顶部的RelativeLayout占据整个屏幕,而LinearLayout占据整个屏幕的一部分.我试图以这样的方式设置GridLayout的子视图的大小,即对于n行和m列,单元格的大小与n,m值以及LinearLayout的宽度和高度直接相关.

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);

不幸的是,创建视图时,mLinearLayout.getMeasuredWidth()不能返回正确的大小.它始终会返回实际设备的屏幕宽度,直到视图完全布置好为止(在这种情况下为时已晚).我已经根据最初完全不正确的值为子单元格视图提供了大小.

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()创建视图并在理论上进行布局.但是,还不能保证它们的视图处于最终正确的位置/大小.

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

推荐答案

您可以将ViewObserver添加到任何视图,在此观察器中,有一个onGlobalLayout回调方法,在布局Layout时会调用该方法;

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.
    }
}

这篇关于我们何时知道活动的视图何时布置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆