Android 获取控件宽高的3种方法

  /**
     * 获取控件宽高 此方法会加载onMeasure三次
     *
     * @param v
     * @return 宽高坐标
     */
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        v.measure(w, h);
        int width = v.getMeasuredWidth();
        int height = v.getMeasuredHeight();


    /**
     * 获取控件宽高 此方法会加载onMeasure二次,但是回调函数会回调很多次
     *
     * @param v
     * @return 宽高坐标
     */
        ViewTreeObserver viewTreeObserver = v.getViewTreeObserver();
        viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                int width = v.getMeasuredWidth();
                int height= v.getMeasuredHeight();
                return true;
            }
        });


    /**
     * 获取控件宽高 此方法会加载onMeasure二次,但是回调函数只回调一次
     *
     * @param v
     * @return 宽高坐标
     */
        ViewTreeObserver vto = v.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                v.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                int width = v.getMeasuredWidth();
                int height = v.getMeasuredHeight();
            }
        });

你可能感兴趣的:(Android,控件使用,android,控件宽高)