标签:
很多人在activity主线程中调用getWidth、getMeasuredWidth,却获取不到view的宽高,这是因为此时view还没有完成绘制,当然获取不到,那要怎么办呢?
方法一,自己测量:
int w = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED); int h = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED); view.measure(w, h); int height = view.getMeasuredHeight(); int width = vew.getMeasuredWidth();
方法二,添加绘图监听,绘图结束后获取view的大小:
view.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { public boolean onPreDraw() { view.getViewTreeObserver().removeOnPreDrawListener(this); int height = view.getMeasuredHeight(); int width = view.getMeasuredWidth(); return true; } });
方法三,添加全局布局变化监听:
view.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { view.getViewTreeObserver().removeGlobalOnLayoutListener(this); view.getHeight(); view.getWidth(); } });
标签:
原文地址:http://my.oschina.net/u/2415508/blog/500423