android-获取View的Width和Height-随心
来源:互联网 发布:js触发click事件 a标签 编辑:程序博客网 时间:2024/05/29 09:23
我们知道要在onCreate方法中知道某个View组件的宽度和高度等信息,而直接调用View组件的getWidth()、getHeight()、getMeasuredWidth()、getMeasuredHeight()、getTop()、getLeft()等方法是无法获取到真实值的,只会得到0。这是因为View组件布局要在onResume回调后完成。下面提供实现方法,onGlobalLayout回调会在布局完成时自动调用,代码如下。
button2.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {//由于这里会被调用两次,我们只需用到一次,加个标志boolean isFirst = true;public void onGlobalLayout() {if (isFirst) {int width = button2.getWidth();int height = button2.getHeight();Log6.v("getViewTreeObserver获得---width:"+width+"---height:"+height);isFirst = false;}}});另外还有一种方法可获得到,不过获取到的都是wrap_content的大小,代码如下。
public void measureView(View child) { ViewGroup.LayoutParams p = child.getLayoutParams(); if (p == null) { p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width); int lpHeight = p.height; int childHeightSpec; if (lpHeight > 0) { childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY); } else { childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } child.measure(childWidthSpec, childHeightSpec); }measureView(main_linear);width = main_linear.getMeasuredWidth();height = main_linear.getMeasuredHeight();
0 0
- android-获取View的Width和Height-随心
- 获取View的height 和width
- 获取View的height 和width
- Android 屏幕 width 和 height 的获取
- 在view中获取height和width的方法
- onCreate()过程中获取View的width和Height
- 在onCreate()方法中获取view的width和height
- Android 在初始化Activity时获取View的width和height
- Android解决在onCreate()中获取View的width、Height为0的方法
- 在Activity的onCreate方法中获取View的width和height
- 在onCreate()过程中获取View的width和Height为0的4种解决方法
- 解决 获取View的width和Height为0的4种方法
- 解决在onCreate()过程中获取View的width和Height为0的方法
- android在oncreate()方法中获取view的宽高width,height
- 获取View的width,height的正确方式
- 知识点滴记录:onCreate()过程中获取View的width和Height为0
- 如何解决在onCreate()中获取View的width和Height为0?
- android view的width或者height变化的动画
- oracel net manager出问题的解决办法
- android调用web service(cxf)实例
- C++手记--快速入门
- 【转载于<小锋刚>博客园】C#遍历ContextMenuStrip右键菜单中包含子菜单的所有菜单并添加事件
- 简单明了 -- mysql中的limit用法
- android-获取View的Width和Height-随心
- 第一个webservice案例
- 1.cocos2d CCLayer 的创建
- 如何在PCB上通过器件选择和布线达到降低噪声的目的?
- java的内存分析
- 使用NSMethodSignature和NSInvocation实现消息转发
- 如何在github上发起一个pull request
- OpenCV c接口与c++接口
- OpenCV成长之路(3):模仿PhotoShop中魔术棒工具