Android获取View宽高的几种方式
2016-01-15 14:30
453 查看
有时我们会有基于这样的需求,当Activity创建时,需要获取某个View的宽高,然后进行相应的操作,但是我们在onCreate,onStart中获取View的大小,获取到的值都是0,只是由于View的绘制工程还未完成,和在onCreate中弹出Dialog或者PopupWindow会报一个Activity not running原理类似。接下来就为大家介绍几种获取View宽高的方法:一、重写Activity中的onWindowFocusChanged,当Activity获取到焦点的时候View已经绘制完成,也能获取到View的准确宽高了。同样的Dialog和PopupWindow也可以在这里弹出,需要注意的是这个方法会调用多次,当hasFocus为true时,才可进行相应的操作
@Override 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()); } }); }
相关文章推荐
- android中心类库
- Android圆角矩形创建工具RoundRect类
- Android用ContentProvider开发通讯录
- Android菜鸟进阶之路一-Android基础
- 深入理解Android View
- Android 第三方开源库收集整理(转)
- Android沉浸式状态栏实现
- Android TextWatcher使用详解
- Android Studio开发工具的设置
- Android LruCache 缓存 类 源码 注解 分析
- Android退出应用最优雅的方式
- android studio 开启genymotion 出现"failed to create framebuffer image"
- android 顶部状态栏遮盖
- Android开发之EditText属性详解
- <安卓那点事>简单短信发送器
- android自定义控件学习(一)单行横向标签并做溢出处理
- 解决支付宝WEB支付界面模块在Android上自动滑动到登录模块的问题
- Android开发中使用软引用和弱引用
- Android缓存文件的存放
- Android如何实现音频输出切换