Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 如何取得初始狀態下 View 的寬高

編輯:關於 Android 程式設計

在自訂 View 或下拉刷新等情境中,常常需要在初始化階段取得 View 的寬高。然而,在 View 尚未完成 measure 與 layout 之前,getHeight 與 getMeasuredHeight 通常會回傳 0。

為何取得到 0

View 的測量結果要在 measure 之後才有意義,而實際高度則要等 layout 完成後才會確定。因此,若只是 inflate 完版面就立即取得高度,往往會得到 0。

View 測量結果

手動觸發測量

若希望在初始化時取得高度,可以自行呼叫 measure。常見做法是建立一個 measureView 方法,先取得 LayoutParams,再根據寬高建立 MeasureSpec,最後呼叫 child.measure。

private void measureView(View child) {
    ViewGroup.LayoutParams lp = child.getLayoutParams();
    if (lp == null) {
        lp = new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        );
    }
    int widthSpec = ViewGroup.getChildMeasureSpec(0, 0, lp.width);
    int heightSpec;
    if (lp.height > 0) {
        heightSpec = MeasureSpec.makeMeasureSpec(lp.height, MeasureSpec.EXACTLY);
    } else {
        heightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
    }
    child.measure(widthSpec, heightSpec);
}

呼叫 measureView 之後,就可以透過 getMeasuredHeight 取得測量高度。

注意實際顯示差異

需要注意的是,手動測量的結果不一定等同最終畫面高度。當 View 被加入父容器後,父容器可能會依自身規則重新配置子 View,導致最終寬高與手動測量結果不同。

加入父容器後的高度 未加入父容器時的測量 水平容器中的測量結果

因此,若只是需要在初始化階段做初步判斷,手動 measure 是可行方案;若需要取得最終顯示尺寸,則應在 layout 完成後再取得。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved