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

Android onLayout 與 layout 方法解析

編輯:關於 Android 程式設計

onLayout 是 ViewGroup 用來排列子 View 的方法,layout 則是 View 決定自身位置與大小的方法。自訂 ViewGroup 時,通常需重寫 onLayout,並搭配 onMeasure 完成測量與配置。

方法差異

onLayout 的參數 l、t、r、b 代表父容器可用空間的左上與右下座標。呼叫子 View 的 layout 時,傳入相對於父容器的座標,即可決定子 View 的顯示位置。

protected void onLayout(boolean changed, int l, int t, int r, int b) {
    for (int i = 0; i < getChildCount(); i++) {
        View child = getChildAt(i);
        child.layout(l, t, l + 100, t + 100);
        l += 120;
    }
}

上例讓子 View 水平排列,並保留間距。實際開發中,可先呼叫 measure 取得子 View 測量結果,再依需求動態計算位置。

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