package com.example.flowlayout;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
public class Flowlayout extends FrameLayout {
private int H_DISTANCE = 20;//垂直间距
private int V_DISTANCE = 20;//水平间距
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 void addTextView(String keys)
{
TextView textView = (TextView) View.inflate(getContext(),
R.layout.flow_item, null);
textView.setText(keys);
//布局宽高自适应
LayoutParams params = new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
textView.setLayoutParams(params);
addView(textView);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
int width = getWidth();//获取本控件的宽度 用于计算换行
int row = 0;
int disWidth = H_DISTANCE;//子控件左边的坐标
for (int i = 0; i < getChildCount(); i++) {
View view = getChildAt(i);//查找子控件
int viewWidth = view.getWidth();
int viewHeight = view.getHeight();
if (disWidth+viewWidth > width)//接下来的控件的右边坐标超过了屏幕宽度
{
row++;//行数增加
disWidth = H_DISTANCE;//还原左边坐标
}
int viewTop = row * viewHeight+row * V_DISTANCE;
view.layout(disWidth,viewTop,disWidth+viewWidth,
viewTop+viewHeight);
disWidth += (viewWidth+H_DISTANCE);//记录下一次子控件的坐标
}
}
}