在onCreate中获取控件的宽高等信息的几种方法

我们都知道,View的onMeasure()方法是在onCreate()方法之后调用,我们在onCreate()中获取控件的width和height总是为0。 解决这个问题,有以下几种方法:

        // 根据提供的大小值和模式创建一个测量值(格式)
        int w = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
        button.measure(w, h); // 让button先mesure
        int width =button.getMeasuredWidth();
        Log.i(TAG, "-=-=-=-=-= width" + width);

注册布局全局监听,即将draw时回调此方法进行测量

        final ViewTreeObserver vto = button.getViewTreeObserver();
        vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
	            // 注意要移出监听,否则会多次调用,因为是view tree全局监听,每个子view的变化都会触发这个监听。
                button.getViewTreeObserver().removeOnPreDrawListener(this);
                int width = button.getWidth();
                int measuredWidth = button.getMeasuredWidth();
                Log.i(TAG, "\n\n" + "draw ===== width:" + width + "," + "measureWidth" +
                        measuredWidth);
                return true;
            }
        });

注册布局全局监听,当measure完毕后(即layout前)回调此方法进行测量

        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                button.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                int width = button.getWidth();
                int measuredWidth = button.getMeasuredWidth();
                Log.i(TAG, "\n\n" + "layout ===== width:" + width + "," + "measureWidth" +
                        measuredWidth);
            }
        });

有关ViewTreeObserver请看:ViewTreeObserver监听ViewTree 参考Blog: http://blog.csdn.net/johnny901114/article/details/7839512

最后更新于