欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

View - 获取某个view 宽高的四种方法

程序员文章站 2022-03-25 16:41:44
...

1.Activity# onWindowFousChanged


   @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if(hasFocus){
            int height = main_viewpager.getMeasuredHeight();
            int width = main_viewpager.getMeasuredWidth();
        }
    }

多次调用在窗口得到焦点和失去焦点

2.view.post(runnable)

  @Override
    protected void onStart() {
        super.onStart();
        main_viewpager.post(new Runnable() {
            @Override
            public void run() {
                int height = main_viewpager.getMeasuredHeight();
                int width = main_viewpager.getMeasuredWidth();
            }
        });
    }

3.ViewTreeObserver


 @Override
    protected void onStart() {
        super.onStart();

        ViewTreeObserver viewTreeObserver = main_viewpager.getViewTreeObserver();

        viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                main_viewpager.getViewTreeObserver().removeOnGlobalLayoutListener(this);

                int height = main_viewpager.getMeasuredHeight();
                int width = main_viewpager.getMeasuredWidth();
            }
        });
    }

View 树的状态改变,onGlobalLayout 会被调用多次

4.view.measure(int widthMeasurespec, int heightMeasureSpec)

相关标签: 视图

上一篇: # CSS 3D 动画

下一篇: MySQL之视图