美文网首页
获取View宽高

获取View宽高

作者: ShawZ | 来源:发表于2018-11-26 12:11 被阅读0次

    在onCreate()中获取View宽高

    两种方法:

    1.使用View.post(Runable runable)方法

            imageView.post(new Runnable() {
                @Override
                public void run() {
                    Log.d(TAG, "run: width = " + imageView.getWidth());
                    Log.d(TAG, "run: measuredWidth = " + imageView.getMeasuredWidth());
                }
            }); 
    

    2.使用ViewTreeObserver:

    ViewTreeObserver observer = imageView.getViewTreeObserver();
            observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    Log.d(TAG, "onGlobalLayout: width = " + imageView.getWidth());
                    Log.d(TAG, "onGlobalLayout: measuredWidth = " + imageView.getMeasuredWidth());
                }
            });
    

    3.可以覆写onWindowFocusChanged方法

        @Override
        public void onWindowFocusChanged(boolean hasFocus) {
            super.onWindowFocusChanged(hasFocus);
            Log.d(TAG, "onWindowFocusChanged: width = " + imageView.getWidth());
            Log.d(TAG, "onWindowFocusChanged: measuredWidth = " + imageView.getMeasuredWidth());
        }
    

    ==注意==:ViewTreeObserver和onWindowFocusChanged会被调用多次

    相关文章

      网友评论

          本文标题:获取View宽高

          本文链接:https://www.haomeiwen.com/subject/nbtbqqtx.html