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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wangtao0921/article/details/80321519

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)

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试

关闭