標籤:
onLayout方法是ViewGroup中子View的布局方法,用於放置子View的位置。放置子View很簡單,只需在重寫onLayout方法,然後擷取子View的執行個體,調用 子View的layout方法實現布局。在實際開發中,一般要配合onMeasure測量方法一起使用。
onLayout方法:
@Overrideprotected abstract void onLayout(boolean changed, int l, int t, int r, int b);
該方法在ViewGroup中定義是抽象函數,繼承該類必須實現onLayout方法,而ViewGroup的onMeasure並非必須重寫的。View的放置都是根據一個矩形空間放置的,onLayout傳下來的l,t,r,b分別是放置父控制項的矩形可用空間(除去margin和padding 的空間)的左上方的left、top以及右下角right、bottom值。
layout方法:
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
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布局:
<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" /> </com.example.layout.MyViewGroup></RelativeLayout>
效果:
MyViewGroup是藍色,兩個子View分別為紅色和綠色。
在自訂View中,onLayout配合onMeasure方法一起使用,可以實現自訂View的複雜布局。自訂View首先調用onMeasure進行測量,然後調用onLayout方法,動態擷取子View和子View的測量大小,然後進行layout布局。
Android的onLayout、layout方法講解