view.post获取height=0

view获取宽高常见的方式:

view.post(new Runnable() {  
    @Override  
    public void run() {  
        view.getHeight();  
    }  
});

但是这种方式不是万能的,有时候对于ViewGroup无效,这时候要借助viewgroup的onMeasure方法:

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            View view = getChildAt(i);
            measureChild(view, widthMeasureSpec, heightMeasureSpec);
            Log.i("test", px2dip(view.getMeasuredHeight()) + "--" + px2dip(view.getHeight()));
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        Log.i("test", px2dip(getMeasuredHeight()) + "");
    }

/**
     * 将像素转换成dp
     * 
     * @param context
     * @param pxValue
     * @return
     */
    public int px2dip(float pxValue) {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

注意这里使用的是getMeasuredHeight,不是getHeight,计算的是子view的原始高度,不是显示高度。

对您有帮助,看心情打赏

你可能感兴趣的:(view.post获取height=0)