ViewGroup中,会对存放在它其中的子View(childView)进行摆放。常见的ViewGroup有LinearLayout,RelativeLayout,FrameLayout。
实现自定义一个ViewGroup时,可以继承LinearLayout或者RelativeLayout等现有的ViewGroup。也可以直接继承类ViewGroup。
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// TODO Auto-generated method stub
int childCount = getChildCount() ;
int startLeft = 0 ;//设置每个子View的起始横坐标
int startTop = 10 ; //每个子View距离父视图的位置 , 简单设置为10px吧 。 可以理解为 android:margin=10px ;
Log. v(TAG, "------- onLayout start ") ;
for(int i=0 ;i<childCount ; i++){
View child = getChildAt(i) ; //获得每个对象的引用
child.layout(startLeft, startTop, startLeft+child.getMeasuredWidth(), startTop+ child.getMeasuredHeight()) ;
startLeft =startLeft+ child.getMeasuredWidth() + 10; //校准startLeft值,View之间的间距设为10px ;
Log. v(TAG, "------- onLayout startLeft " +startLeft) ;
}
}
参考资料:
public void layout (int l, int t, int r, int b)
Assign a size and position to a view and all of its descendants(子节点)
This is the second phase of the layout mechanism. (The first is measuring). In this phase, each parent calls layout on all of its children to position them. This is typically done using the child measurements that were stored in the measure pass().
Derived classes should not override this method. Derived classes with children should override onLayout. In that method, they should call layout on each of their children.
Parameters
l Left position, relative to parent
t Top position, relative to parent
r Right position, relative to parent
b Bottom position, relative to parent
http://blog.csdn.net/androiddevelop/article/details/8108970
http://blog.csdn.net/aaa2832/article/details/7849400
http://blog.csdn.net/aaa2832/article/details/7844904