Instantly share code, notes, and snippets.

Embed
What would you like to do?
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by amyu- on 2015/04/19.
*/
public class GeneralViewGroup extends ViewGroup {
private int mParentWidth;
private int mMargin;
private OnItemClickListener mOnItemClickListener;
public GeneralViewGroup(Context context) {
this(context, null, 0);
}
public GeneralViewGroup(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public GeneralViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int childCount = getChildCount();
int height = 0;
int right = 0;
int viewWidth = MeasureSpec.getSize(widthMeasureSpec);
if (childCount > 0) {
height = getChildAt(0).getMeasuredHeight() + mMargin;
} else {
return;
}
for (int i = 0; i < childCount; i++) {
View view = getChildAt(i);
view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
right += view.getMeasuredWidth() + mMargin;
if (viewWidth < right) {
right = view.getMeasuredWidth() + mMargin;
height += view.getMeasuredHeight() + mMargin;
}
}
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), height);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int bottom = 0;
int right = 0;
int childCount = getChildCount();
if (childCount > 0) {
bottom = getChildAt(0).getMeasuredHeight() + mMargin;
} else {
return;
}
for (int i = 0; i < childCount; i++) {
View view = getChildAt(i);
right += view.getMeasuredWidth() + mMargin;
if (mParentWidth < right) {
bottom += view.getMeasuredHeight() + mMargin;
right = view.getMeasuredWidth() + mMargin;
}
view.layout(
right - view.getMeasuredWidth(),
bottom - view.getMeasuredHeight(),
right,
bottom);
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mParentWidth = w;
super.onSizeChanged(w, h, oldw, oldh);
}
@Override
public void addView(View child) {
child.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (mOnItemClickListener == null) {
return;
}
mOnItemClickListener.onItemClick(view);
}
});
super.addView(child);
}
public void setMargin(int margin) {
mMargin = margin;
invalidate();
}
private void initView() {
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
mOnItemClickListener = onItemClickListener;
}
public interface OnItemClickListener {
void onItemClick(View view);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment