onLayout方法是ViewGroup中子View的佈局方法,用於放置子View的位置。放置子View很簡單,只需在重寫onLayout方法,而後獲取子View的實例,調用子View的layout方法實現佈局。在實際開發中,通常要配合onMeasure測量方法一塊兒使用。html
onLayout方法:android
?ide
1函數 2佈局 3spa |
@Override code protected abstract void onLayout( boolean changed, xml int l, int t, int r, int b); htm |
該方法在ViewGroup中定義是抽象函數,繼承該類必須實現onLayout方法,而ViewGroup的onMeasure並不是必須重寫的。View的放置都是根據一個矩形空間放置的,onLayout傳下來的l,t,r,b分別是放置父控件的矩形可用空間(除去margin和padding的空間)的左上角的left、top以及右下角right、bottom值。繼承
layout方法:
?
1 |
public void layout( int l, int t, int r, int b); |
該方法是View的放置方法,在View類實現。調用該方法須要傳入放置View的矩形空間左上角left、top值和右下角right、bottom值。這四個值是相對於父控件而言的。例如傳入的是(10, 10, 100, 100),則該View在距離父控件的左上角位置(10, 10)處顯示,顯示的大小是寬高是90(參數r,b是相對左上角的),這有點像絕對佈局。
日常開發所用到RelativeLayout、LinearLayout、FrameLayout...這些都是繼承ViewGroup的佈局。這些佈局的實現都是經過都實現ViewGroup的onLayout方法,只是實現方法不同而已。
下面是一個自定義ViewGroup的Demo,用onLayout和layout實現子View的水平放置,間隔是20px
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public class MyViewGroup extends ViewGroup { // 子View的水平間隔 private final static int padding = 20 ; public MyViewGroup(Context context, AttributeSet attrs) { super (context, attrs); // TODO Auto-generated constructor stub } @Override protected void onLayout( boolean changed, int l, int t, int r, int b) { // TODO Auto-generated method stub // 動態獲取子View實例 for ( int i = 0 , size = getChildCount(); i < size; i++) { View view = getChildAt(i); // 放置子View,寬高都是100 view.layout(l, t, l + 100 , t + 100 ); l += 100 + padding; } } } |
Activity的XML佈局:
?
1 2 3 4 5 6 7 8 9 10 |
<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http://schemas.android.com/tools" android:layout_width= "match_parent" android:layout_height= "match_parent" android:padding= "10dp" > <com.example.layout.myviewgroup android:layout_width= "match_parent" android:layout_height= "100dp" android:background= "#0000ff" > <view android:layout_width= "match_parent" android:layout_height= "match_parent" android:background= "#ff0000" > <view android:layout_width= "match_parent" android:layout_height= "match_parent" android:background= "#00ff00" > </view></view></com.example.layout.myviewgroup> </relativelayout> |
效果如圖所示:

上圖MyViewGroup是藍色,兩個子View分別爲紅色和綠色。
在自定義View中,onLayout配合onMeasure方法一塊兒使用,能夠實現自定義View的複雜佈局。自定義View首先調用onMeasure進行測量,而後調用onLayout方法,動態獲取子View和子View的測量大小,而後進行layout佈局。