-2

在 Activity 加载后,我正在尝试我的应用程序格式化屏幕中的一些图像。问题是在内部onCreate()onResume()方法我ImageView的宽度和高度=0。调整视图大小后如何运行一些代码?我测试onPostResume()但它不起作用=(

4

1 回答 1

3

Android 中的视图不像 Blackberry 或 iPhone 那样具有固定的大小/位置;相反,它们是动态布局的。布局发生的时间远远晚于onCreate/onResume,理论上可以发生很多次。每个视图都有方法onMeasure并且onLayout负责。只有在onLayout方法返回后,您才能知道视图的大小和位置。在此之前,视图的大小为 0,位置为 0(如您所见)。

所以尝试获取 ImageView 的大小是没有意义的,onCreate/onResume因为onLayout那时还没有被调用。

相反,onLayout像这样覆盖并在那里做你的事情:

public class MyImageView extends ImageView {
    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        // at this point size and position are known
        int h = getHeight();
        int w = getWidth();
        doSomethingCool(h,w);
    }
}
于 2011-07-15T22:46:29.937 回答