Android中oncreate中如何获得控件高度或宽度?

onCreate函数只是提供了数据初始化的机会,此时还没有正式绘制图形。在图形尚未渲染的情况下,getWidth()或getHeight()得到的值为0。如果需要自适应屏幕,需要一进入界面就得到父控件大小,然后需要在onCreate中动态设置子控件大小。


方法1:利用ViewTreeObserver类的addOnPreDrawListener接口。(好)

ViewTreeObserver vto = hscrollview.getViewTreeObserver();

                   vto.addOnPreDrawListener(newViewTreeObserver.OnPreDrawListener() {

                            @Override

                            publicboolean onPreDraw() {

                                     if(hasMeasured == false){

                                               intwid = hscrollview.getWidth();

                                               inthei = hscrollview.getHeight();

                                               if(wid != 0 && hei != 0){

                                                        hasMeasured= true;

                                               }

                                     }

                                     returntrue;

                            }

                   });

 

方法2:利用ViewTreeObserver类的addOnGlobalLayoutListener接口。(好)

和方法1类似。

 

方法3:postDelayed延迟一定时候后获得控件大小再设置。(不太好)


参考: 

http://www.cnblogs.com/wt616/archive/2012/05/11/2496180.html

http://blog.sina.com.cn/s/blog_4172d3d60101h15p.html

你可能感兴趣的:(android)