手机网站产品展示模板,一键开发小程序,公众号制作编辑器,前端什么证书含金量高view在绘制完成后才会有自己的宽高#xff0c;所以在onCreate中要获得view的宽高可以通过以下4中方法#xff1a;
1、ViewTreeObserver#xff1a;监听界面绘制事件#xff0c;在layout时调用#xff0c;使用完毕后记得removeListener
2、view.post#xff0c;因为runn…view在绘制完成后才会有自己的宽高所以在onCreate中要获得view的宽高可以通过以下4中方法
1、ViewTreeObserver监听界面绘制事件在layout时调用使用完毕后记得removeListener
2、view.post因为runnable对象会在view的measure、layout后触发
3、重写onLayout方法
4、使用getMeasuredWidth、getMeasuredHeight获得测量后的宽高可能跟view的真实宽高有差距
当Activity创建时需要获取某个View的宽高然后进行相应的操作但是我们在onCreateonStart中获取View的大小获取到的值都是0只是由于View的绘制工程还未完成和在onCreate中弹出Dialog或者PopupWindow会报一个Activity not running原理类似。
第一种重写Activity中的onWindowFocusChanged当Activity获取到焦点的时候View已经绘制完成也能获取到View的准确宽高了。同样的Dialog和PopupWindow也可以在这里弹出需要注意的是这个方法会调用多次当hasFocus为true时才可进行相应的操作 /prepre namecode classjavaOverride public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus) { System.out.println(onWindowFocusChanged width tvTest.getWidth() height tvTest.getHeight()); } }
第二种
/** * 会执行多次 */ private void getSize1() { ViewTreeObserver vto tvTest.getViewTreeObserver(); vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { Override public boolean onPreDraw() { int height tvTest.getMeasuredHeight(); int width tvTest.getMeasuredWidth(); System.out.println(height height); System.out.println(width width); return true; } }); } 第三种
private void getSize2() { ViewTreeObserver viewTreeObserver tvTest.getViewTreeObserver(); viewTreeObserver .addOnGlobalLayoutListener(new OnGlobalLayoutListener() { Override public void onGlobalLayout() { tvTest.getViewTreeObserver() .removeGlobalOnLayoutListener(this); System.out.println(onGlobalLayout width tvTest.getWidth() height tvTest.getHeight()); } }); }
第四种 private void getSize3() { tvTest.post(new Runnable() { Override public void run() { System.out.println(postDelayed width tvTest.getWidth() height tvTest.getHeight()); } }); }