1. 程式人生 > >獲取某個view的高度或者寬度

獲取某個view的高度或者寬度

方法一

在activity的onWindoFocusChanged中獲取寬高.此方法會被呼叫多次.在activity得到焦點或者失去焦點的時候均會呼叫.程式碼如下

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus){
            int width=testBtn.getMeasuredWidth();
            int height=testBtn.getMeasuredHeight();
            Log.d(TAG, "onWindowFocusChanged: width="+width);
            Log.d(TAG, "onWindowFocusChanged: height="+height);
        }
    }

方法二

通過post將一個runnable投遞到訊息佇列尾部
程式碼如下:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_touch_test);
        testBtn= findViewById(R.id.btn_test);
        testBtn.post(new Runnable() {
            @Override
            public void run() {
                int width=testBtn.getMeasuredWidth();
                int height=testBtn.getMeasuredHeight();
                Log.d(TAG, "onWindowFocusChanged: width="+width);
                Log.d(TAG, "onWindowFocusChanged: height="+height);
            }
        });
    }

方法三

ViewTreeObserver
使用ViewTreeObserver的眾多回調可以完成這個功能,比如使用onGlobalLayoutListener這個介面.當view樹發生改變,或者View樹內部的view的可見性發生改變時,此方法將被呼叫.此方法可能會被呼叫多次:

    @Override
    protected void onStart() {
        super.onStart();
        ViewTreeObserver viewTreeObserver=testBtn.getViewTreeObserver();
        viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int width=testBtn.getMeasuredWidth();
                int height=testBtn.getMeasuredHeight();
                Log.d(TAG, "onWindowFocusChanged: width="+width);
                Log.d(TAG, "onWindowFocusChanged: height="+height);
            }
        });
    }

方法四

手動呼叫view.measure 進行measure得到view的寬高.方法較複雜,此處不表