獲取某個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的寬高.方法較復雜,此處不表


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM