Android 获取View高度的4种方法

1 通过 looper 队列

    /**
     * 通过 looper 队列
     */
    private void getHeight1() {
        tvText.post(new Runnable() {
            @Override
            public void run() {
                int height = tvText.getHeight();
                Log.i(TAG, "MainActivity;getHeight1;height=" + height);
            }
        });
    }

2  当视图树的布局发生改变时

    /**
     * 当视图树的布局发生改变时
     */
    private void getHeight2() {
        tvText.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                tvText.getViewTreeObserver().removeOnGlobalLayoutListener(this);

                int height = tvText.getHeight();
                Log.i(TAG, "MainActivity;getHeight2;height=" + height);
            }
        });
    }

3  当视图树的进行绘制时

    /**
     * 当视图树的进行绘制时
     */
    private void getHeight3() {
        tvText.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                tvText.getViewTreeObserver().removeOnPreDrawListener(this);

                int height = tvText.getHeight();
                Log.i(TAG, "MainActivity;getHeight3;height=" + height);
                return false;
            }
        });
    }

4 view 布局改变时

    /**
     * view 布局改变时
     */
    private void getHeight4() {
        tvText.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                tvText.removeOnLayoutChangeListener(this);
                int height = tvText.getHeight();
                Log.i(TAG, "MainActivity;getHeight4;height=" + height);
            }
        });
    }
发布了19 篇原创文章 · 获赞 2 · 访问量 1169

猜你喜欢

转载自blog.csdn.net/xyyh6600/article/details/104470356