定义的流式布局的类(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();//清空