问题描述
我有一个绘制一个滚动的位图到屏幕上的自定义视图。为了初始化它,我需要传递的大小父布局对象的像素。但是,在的onCreate和onResume功能,布局尚未拟定着呢,所以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.
作为一种解决办法,我添加了一个处理程序,等待一秒钟,然后进行测量。这工作,但它的马虎,我不知道多少,我可以修剪的时候我才结束了之前的laout被绘制。
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 laout 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() {
this.layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int width = layout.getMeasuredWidth();
int height = layout.getMeasuredHeight();
}
});
这篇关于你怎么能知道什么时候布局已经绘就?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!