写的比较基础, 备忘使用。
public class FlowLayout extends ViewGroup {
public FlowLayout(Context context) {
this(context, null);
}
public FlowLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
//测量所有子View的总高度
measureChildren(0, 0);
//当前行前面所有控件宽度
int allWidth = 0;
//当前行前面所有控件高度
int allHeight = 0;
//遍历所有子View
for (int i = 0; i < getChildCount(); i++) {
//拿到子控件
View view = getChildAt(i);
//先判断是否换行, 如果控件在一行放不下,便放入下一行
if (allWidth + view.getMeasuredWidth() >= getMeasuredWidth()) {
//换行
//换行的时候,前面的总宽度重新设置为0,宽度加上一行的高度
allWidth = 0;
//高度加上之前的高度
allHeight += view.getMeasuredHeight();
}
//换行时变高度, 不换行时只变宽度
//设置前后左右的控件的位置 , 属性先后顺序是:左上右下
view.layout(allWidth,
allHeight,
allWidth + view.getMeasuredWidth(),
allHeight + view.getMeasuredHeight());
//之前总宽度加上这次的宽度, 等于最新的宽度
allWidth += view.getMeasuredWidth();
}
}
}
如果写的死数据,可以在xml文件中自定义控件添加Textview ,
可以使用shape绘制一个圆角边框, 使用backbackground 引用圆角
删除所有视图 group的方法, removeViews;
select.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView textView = new TextView(HomePageActivity.this);
//设置输出框的值
String s = home_edit.getText().toString();
textView.setText(s);
//设置背景
textView.setBackgroundResource(R.drawable.bg);
ViewGroup.MarginLayoutParams layoutParams = new ViewGroup.MarginLayoutParams(ViewGroup.MarginLayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
//设置padding
textView.setPadding(10, 0, 10, 10);
//设置margins
layoutParams.setMargins(10, 10, 10, 10);
textView.setLayoutParams(layoutParams);
flow_layout.addView(textView);
}
});