自定义流式布局+添加+清空

定义的流式布局的类(FlowView)

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewGroup;
//-------
public class FlowView extends ViewGroup {
    //设置默认的间距
    int sLeftMargin = 20;
    int sTopMargin = 20;

    public FlowView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //所有子view 都是 多宽,多高, 内部调用了measureChild方法
        measureChildren(widthMeasureSpec, heightMeasureSpec);//获取子view的宽高
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        ///赋值原来的边距
        int yleftMargin = sLeftMargin;//左边距
        int ytopMargin = sTopMargin;//上边距
        //getChildCount() 返回子view的个数
        //getChildAt(int index).可以拿到index上的子view。
        for (int i = 0; i < getChildCount(); i++) {
            //得到每个 子view 的宽高
            int widthChild = getChildAt(i).getMeasuredWidth();
            int heightChild = getChildAt(i).getMeasuredHeight();
            //原来的左边距+设置的左边距+孩子的宽度>控件的宽
            if (yleftMargin+sLeftMargin+widthChild>getWidth()){//换行
                yleftMargin=sLeftMargin;
                ytopMargin+=sTopMargin+heightChild;
                //左、上 右、下
                getChildAt(i).layout(yleftMargin,ytopMargin,yleftMargin+widthChild,ytopMargin+heightChild);
            }else{//不换行
                getChildAt(i).layout(yleftMargin,ytopMargin,yleftMargin+widthChild,ytopMargin+heightChild);
            }
            yleftMargin+=sLeftMargin+widthChild;
        }
    }
}

添加 子控件(TextView)

        TextView textView=new TextView(MainActivity.this);//定义Textview
        textView.setText(data);//设置shuju8
        flowView.addView(textView);//添加view

清空 布局

 flowView.removeAllViews();//清空
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值