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);
            }
        });
    }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值