viewgroup浅析

来源:互联网 发布:java因式分解 编辑:程序博客网 时间:2024/05/16 08:58

查阅了网上的相关资料,在此做下笔记:

1. measure(并调用子视图的measure)

2. layout(并调用子视图的layout)

3 dispatchDraw(对canvas进行操作(translate),绘制子视图)


下边是我写的一个例子

public class CustomLayout extends View {public CustomLayout(Context context) {super(context);initView();}public CustomLayout(Context context, AttributeSet attrs) {super(context, attrs);initView();}public void initView() {mChildren = new ArrayList<View>();Context context = getContext();Button button = new Button(context); {ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,   ViewGroup.LayoutParams.WRAP_CONTENT);button.setLayoutParams(params);}button.setText("hello");addView(button);TextView tv = new TextView(context); {ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,   ViewGroup.LayoutParams.WRAP_CONTENT);tv.setLayoutParams(params);}tv.setText("world");addView(tv);}public void addView(View v) {mChildren.add(v);}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {super.onMeasure(widthMeasureSpec, heightMeasureSpec);int count = mChildren.size();for (int i=0; i < count; i++) {View v = mChildren.get(i);v.measure(v.getLayoutParams().width, v.getLayoutParams().height);}}@Overrideprotected void onLayout(boolean changed, int left, int top, int right, int bottom) {int count = mChildren.size();for (int i=0; i < count; i++) {View v = mChildren.get(i);v.layout(left, top, left+v.getMeasuredWidth(), top+v.getMeasuredHeight());top += v.getMeasuredHeight() + 5;}}@Overridepublic void draw(Canvas canvas) {super.draw(canvas);dispatchDraw(canvas);}@Overrideprotected void dispatchDraw(Canvas canvas) {//super.dispatchDraw(canvas);int count = mChildren.size();for (int i=0; i < count; i++) {View v = mChildren.get(i);canvas.save();canvas.translate(v.getLeft(), v.getTop());v.draw(canvas);canvas.restore();}}List<View> mChildren;}


效果图: