自定义ViewGroup
2014-08-31 20:41 ttylinux 阅读(778) 评论(0) 编辑 收藏 举报定义一个自定义View组件,如果只是关注这个View的外观和大小,那么,要重写onDraw,onMeasure这两个方法。比如,我自定义了一个LabelView。
自定义完View之后,该View就可以像TextView之类的在一个ViewGroup中被使用了。
ViewGroup中,会对存放在它其中的子View(childView)进行摆放。常见的ViewGroup有LinearLayout,RelativeLayout,FrameLayout。
那么,如果要实现一个自定义的ViewGroup呢?
实现自定义一个ViewGroup时,可以继承LinearLayout或者RelativeLayout等现有的ViewGroup。也可以直接继承类ViewGroup。
在实现自定义ViewGroup时,要重写onLayout。系统回调你自己实现的onLayout的目的,即执行其中实现布局的代码。
例如:系统会回调该方法,来执行该ViewGroup对其中的childView的布局。系统执行下述onLayout中的布局代码后,
达到的布局效果如下图:
@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)
Added in API level 1
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
版权声明:
作者:ttylinux
本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。