package movie.bw.com.week3;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
public class FlowLayout extends FrameLayout {
private int space;
private int textsize;
private TypedArray array;
private String bg;
private FlowListener flowListener;
public FlowLayout(Context context) {
super(context);
}
public FlowLayout(Context context,AttributeSet attrs) {
super(context, attrs);
array = context.obtainStyledAttributes(attrs, R.styleable.flow);
space = (int) array.getDimension(R.styleable.flow_space,0);
textsize = (int) array.getDimension(R.styleable.flow_testSize, 0);
bg = array.getString(R.styleable.flow_bg);
}
public FlowLayout(Context context,AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
array = context.obtainStyledAttributes(attrs, R.styleable.flow);
space = (int) array.getDimension(R.styleable.flow_space,0);
textsize = (int) array.getDimension(R.styleable.flow_testSize, 0);
bg = array.getString(R.styleable.flow_bg);
}
@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 hWidth=0;//每行控件累加的宽度
int rows=0;//行数
for (int i=0;i<getChildCount();i++){
TextView view= (TextView) getChildAt(i);
view.setTextSize(TypedValue.COMPLEX_UNIT_PX,textsize);
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (flowListener!=null){
flowListener.flowclick(view);
}
}
});
int childwidth = view.getWidth();
int childheight = view.getHeight();
hWidth= hWidth+(childwidth+space);//如果累加宽度大于控件宽度 就换行
if (hWidth>width){
rows++;
hWidth= (int) (childwidth+space);//超过之后等于子控件宽度
}
view.layout(hWidth-childwidth,rows*childheight+(rows+1)*space, hWidth, (rows + 1) * childheight + (rows + 1) * space);
}
}
public void setFlowLayout(FlowListener flowListener) {
this.flowListener = flowListener;
}
public void addView(String s){
TextView view = (TextView) View.inflate(getContext(), R.layout.flow_item, null);
view.setText(s);
// 布局自适应
LayoutParams layoutParams = new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
view.setLayoutParams(layoutParams);
addView(view);
}
// 定义接口
public interface FlowListener{
void flowclick(TextView view);
}
}