Android獲取View寬高的幾種方式

jopen 8年前發布 | 8K 次閱讀 Android開發 移動開發

有時我們會有基于這樣的需求,當Activity創建時,需要獲取某個View的寬高,然后進行相應的操作,但是我們在onCreate,onStart中獲取View的大小,獲取到的值都是0,只是由于View的繪制工程還未完成,和在onCreate中彈出Dialog或者PopupWindow會報一個Activity not running原理類似。接下來就為大家介紹幾種獲取View寬高的方法
一、重寫Activity中的onWindowFocusChanged,當Activity獲取到焦點的時候View已經繪制完成,也能獲取到View的準確寬高了。同樣的Dialog和PopupWindow也可以在這里彈出,需要注意的是這個方法會調用多次,當hasFocus為true時,才可進行相應的操作

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            System.out.println("onWindowFocusChanged width="
                    + tvTest.getWidth() + " height=" + tvTest.getHeight());
        }
    }

二、

/**
     * 會執行多次
     */
    private void getSize1() {

        ViewTreeObserver vto = tvTest.getViewTreeObserver();
        vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                int height = tvTest.getMeasuredHeight();
                int width = tvTest.getMeasuredWidth();
                System.out.println("height" + height);
                System.out.println("width" + width);
                return true;
            }

        });
    }

三、

private void getSize2() {
        ViewTreeObserver viewTreeObserver = tvTest.getViewTreeObserver();
        viewTreeObserver
                .addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        tvTest.getViewTreeObserver()
                                .removeGlobalOnLayoutListener(this);
                        System.out.println("onGlobalLayout width="
                                + tvTest.getWidth() + " height="
                                + tvTest.getHeight());
                    }
                });
    }

四、

private void getSize3() {
        tvTest.post(new Runnable() {

            @Override
            public void run() {
                System.out.println("postDelayed width=" + tvTest.getWidth()
                        + " height=" + tvTest.getHeight());
            }
        });

    }

來自: http://blog.csdn.net/soul_code/article/details/50474528

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!