//样子丑了点,但是可以自己改
//随便创个类继承viewgroup实现它的四个方法
public class FlowLayout extends ViewGroup {
//继承viewgroup重写构造方法
public FlowLayout(Context context) {
super(context);
}
public FlowLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
//绘制
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
//测量
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//测量子宽高
measureChildren(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int width = getWidth();//获取宽
int row = 0;//定义常量
int dieth = 18;//左边距
for (int i = 0; i < getChildCount(); i++) {
// 坐标
View view = getChildAt(i);
int viewwidth = view.getMeasuredWidth();//宽
int viewheight = view.getMeasuredHeight();//高
//判断
if (dieth + viewwidth > width) {
row++;
dieth = 18;
}
//左上右下
view.layout(dieth, row * viewheight, viewwidth + dieth, viewheight * (row + 1));
dieth += viewwidth;
}
}
}
//在你需要的布局文件里面定义FlowLayout类的全路径
<com.bawei.liushi.FlowLayout
android:id="@+id/liushi"
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.bawei.liushi.FlowLayout>
///主页面
liushi = findViewById(R.id.liushi);
//清空流式布局
findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
liushi.removeAllViews();
Toast.makeText(MainActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
}
});
//点击按钮添加到流式布局
bt_s.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String text = et_s.getText().toString().trim();
final TextView textView = new TextView(MainActivity.this);
textView.setText(text);
final ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(ViewGroup.MarginLayoutParams.WRAP_CONTENT, ViewGroup.MarginLayoutParams.WRAP_CONTENT);
liushi.addView(textView, params);
textView.setBackgroundResource(R.drawable.sha);
textView.setTextSize(20);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String trim = textView.getText().toString().trim();
Toast.makeText(MainActivity.this, ""+trim, Toast.LENGTH_SHORT).show();
}
});