很多android初学者想获取某个View的高度或者宽度直接在Activity的onCreate()方法直接通过getHeight()或者getMeasureHeight()方法,发现怎么都是0,因为一个.xml文件也要去遍历然后转换成View对象,也就是你获取他的高度和遍历所有的View是异步的,那有没有当然获取呢?答案肯定是有的,getMeasuredHeight()这个方法和getHeight()从字面上看发现就多了Measure字母,而联想到我们自定义View的时候有个onMeasure()方法,这是测试view的大小,所有getMeasuredHeight()方法就是在onMeasure()测量后调用,因此你要在oncreate()方法中去获取某个view的高度,需要人为去通知系统帮你测量,

final View headerView = LayoutInflater.from(this).inflate(R.layout.layout_header, null);
headerView.measure(0, 0);//主动通知系统去测headerView的高度
int measuredHeight = headerView.getMeasuredHeight();


而getHeight()方法是在OnLayout()方法被调用才会执行,因此也给我们提供了方法去获取他的高度:

headerView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int measuredHeight = headerView.getMeasuredHeight();
headerView.getViewTreeObserver()
                .removeGlobalOnLayoutListener(this);//一定要移除,因为onLayout()会执行多次,如果不移除的话 也会被回调多次,而且值还不一样
}
});


更多相关文章

  1. Android的事件传递机制
  2. Android(安卓)Camera开发(一)之基础知识
  3. 关于在Android(安卓)Studio中使用Assets目录下的资源的问题
  4. Android(安卓)性能分析工具之 TraceView 使用说明
  5. 使用Android(安卓)隐藏API和内部 API
  6. android之js与java互相调用
  7. Android基础(14)SurfaceView
  8. Android中引入第三方Jar包的方法(java.lang.NoClassDefFoundErro
  9. Android之Service案例-电话窃听

随机推荐

  1. 安装Android(安卓)时 SDK AVD MANAGER时
  2. [Android]Awind.inc系列android软件破解
  3. 20个Android游戏源码,…
  4. Android(安卓)xml中 @和?区别,style和attr
  5. Android(安卓)代码改变图片颜色android:t
  6. eclipse中关联android源码
  7. Android(安卓)问题汇总
  8. EditText 文字验证
  9. Android(安卓)Gesture Detector
  10. Android中让View匀速旋转