标签:
package myview;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
public class MyViewGroup extends ViewGroup {
private final static String TAG = "MyViewGroup";
private final static int VIEW_MARGIN = 15;
public MyViewGroup(Context context) {
super(context);
}
public MyViewGroup(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyViewGroup(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int height = 0;
Log.d(TAG, "widthMeasureSpec = " + widthMeasureSpec + " heightMeasureSpec" + heightMeasureSpec);
int x = 0;
int row = 1;
for (int index = 0; index < getChildCount(); index++) {
final View child = getChildAt(index);
// measure
child.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
int h = child.getMeasuredHeight();
int width = child.getMeasuredWidth();
x += width;
int measure = MeasureSpec.makeMeasureSpec(x, MeasureSpec.EXACTLY);
if (measure > widthMeasureSpec) {
x = 0;
row++;
}
height = row * (VIEW_MARGIN + h);
}
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) {
final int count = getChildCount();
int row = 0;// which row lay you view relative to parent
int lengthX = arg1; // right position of child relative to parent
int lengthY = arg2; // bottom position of child relative to parent
for (int i = 0; i < count; i++) {
final View child = this.getChildAt(i);
int width = child.getMeasuredWidth();
int height = child.getMeasuredHeight();
lengthX += width + VIEW_MARGIN;
lengthY = row * (height + VIEW_MARGIN);
//if it can‘t drawing on a same line , skip to next line
Log.d(TAG, " left = " + (lengthX - width) + " top = " + (lengthY - height) + " right = " + lengthX + " botom = " + lengthY);
Log.d(TAG, " width " + width + " height = " + height);
if (lengthX > arg3) {
lengthX = width + VIEW_MARGIN + arg1;
row++;
lengthY = row * (height + VIEW_MARGIN);
}
child.layout(lengthX - width, lengthY, lengthX, lengthY + height);
}
}
}
标签:
原文地址:http://www.cnblogs.com/crazysun/p/4315991.html