很多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()会执行多次,如果不移除的话 也会被回调多次,而且值还不一样
}
});