你怎么知道什么时候已经绘制了布局? [英] How can you tell when a layout has been drawn?

查看:35
本文介绍了你怎么知道什么时候已经绘制了布局?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义视图,可以将可滚动位图绘制到屏幕上.为了初始化它,我需要传入父布局对象的像素大小.但是在 onCreate 和 onResume 函数中,Layout 还没有绘制,所以 layout.getMeasuredHeight() 返回 0.

I have a custom view that draws a scrollable bitmap to the screen. In order to initialize it, i need to pass in the size in pixels of the parent layout object. But during the onCreate and onResume functions, the Layout has not been drawn yet, and so layout.getMeasuredHeight() returns 0.

作为一种解决方法,我添加了一个处理程序以等待一秒钟然后进行测量.这有效,但它很草率,我不知道在绘制布局之前我可以修剪多少时间.

As a workaround, i have added a handler to wait one second and then measure. This works, but its sloppy, and I have no idea how much i can trim the time before I end up before the layout gets drawn.

我想知道的是,如何检测布局何时被绘制?是否有事件或回调?

What I want to know is, how can I detect when a layout gets drawn? Is there an event or callback?

推荐答案

您可以向布局添加树观察器.这应该返回正确的宽度和高度.onCreate() 在子视图的布局完成之前被调用.所以宽度和高度还没有计算出来.要获取高度和宽度,请将其放在 onCreate() 方法上:

You can add a tree observer to the layout. This should return the correct width and height. onCreate() is called before the layout of the child views are done. So the width and height is not calculated yet. To get the height and width, put this on the onCreate() method:

    final LinearLayout layout = (LinearLayout) findViewById(R.id.YOUR_VIEW_ID);
    ViewTreeObserver vto = layout.getViewTreeObserver(); 
    vto.addOnGlobalLayoutListener (new OnGlobalLayoutListener() { 
        @Override 
        public void onGlobalLayout() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    layout.getViewTreeObserver()
                            .removeOnGlobalLayoutListener(this);
                } else {
                    layout.getViewTreeObserver()
                            .removeGlobalOnLayoutListener(this);
                }
            int width  = layout.getMeasuredWidth();
            int height = layout.getMeasuredHeight(); 

        } 
    });

这篇关于你怎么知道什么时候已经绘制了布局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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