自动换行LinearLayout

自定义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();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值