自定义View-自动换行LinearLayout
备忘,加强记忆,没调试,只是为了熟悉
public class NextLineLinearLayout extends LinearLayout{
//记录距离父布局的位置
private int left,top,right,bottom;
//存放位置信息
private HashTable ht=new HashTable();
public NextLineLinearLayout (Context context) {
super(context);
}
public NextLineLinearLayout (Context context, int horizontalSpacing,
int verticalSpacing) {
super(context);
}
public NextLineLinearLayout (Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int mWidth=MeasureSpec.getSize(widthMeasureSpec);
int mCount=getChildCount();
int mX=0;
int mY=0;
left=0;
//增加间距
top=5+0;
botton=0;
right=0;
//记录换行的位置
int j=0;
for(int i=0;i<mCount;i++){
View chaildView=getChildAt(i);
childView.measure(MeasureSpec.UNSPECIFIED,MeasureSpec.UNSPECIFIED);
int childeh=childeView.getMeasureHeight();
int childew=childeView.getMeasureWidth();
Position posititon=new Position();
mX+=childew;
left=getLeft(i-j,i);
if(mX>mWidth){
mX=childew;
mY+=(childeh+5);
left=0;
j=i;
}
top=mY;
right=left+childw;
bottoom=mY+childh;
position.top=top;
position.bottom=bottom;
position.left=left;
position.right=right;
ht.put(childeView,position);
}
setMeasuredDimension(mWidth, bottom);
}
@Override
protected LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(0, 0);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int childCount=getChildCount();
for(int i=0;i<childCount;i++){
View child=getChildAt(i);
Position p=(Position)map.get(child);
if(p!=null){
child.layout(p.left,p.top,p.right,p.bottom);
}
}
}
private Class Position{
int left,top,rignt,bottom;
}
private int getLeft(int row,int count){
if(row>0){
return getLeft(row-1,count-1)+getChildAt(count-1).getMeasureWidth+8;
} //到0,返回距离左边的填充
return getPaddingLeft();
}
}