最近在做项目时候遇到了标签布局问题,当时我首选的是用流式布局TagFlowLayout的控件,可是发现不能满足我项目的需求,于是翻看了一下网页写了一个用配合ChekBox来实现多选标签的布局,在这写出来,希望对其他伙伴们有些帮助!
需取效果:
首先:我们需要一个实体类TagBean,确保有id,和name(显示的内容)
public class TagBean {
private String id;
private String name;
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public TagBean(String id, String name) {
this.id = id;
this.name = name;
}
}
然后就可以写我们的自定义布局了,重写ViewGroup,采用onDraw,onMeasure,onLayout等方法类似于流式布局,熟悉流式布局的小伙伴应该so easy,这里就不说太多了,直接上代码:
public class LabelLayout extends ViewGroup {
private int mMaxCheckCount = Integer.MAX_VALUE;
/**
* 竖直方向间距, default is 8.0dp.
*/
private int horizontalSpacing;
/**
* 水平方向间距, default is 4.0dp.
*/
private int verticalSpacing;
//whether or not to draw the divider between labels at horizon.
private boolean enableDivider = false; //是否允许显示分割线 默认不显示
private int dividerColor = 0xffECECEC;
private float dividerHeight;
private int checkboxLayoutId;
//nark checked labels.
private Map<String, Boolean> labelcheckMap;
//mark the first position in a row.
private Set<Integer> rowPositons = new HashSet<>();
//The paint to draw the divider.
Paint dividerPaint;
public LabelLayout(Context context) {
this(context, null);
}
public LabelLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public LabelLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setWillNotDraw(false);
labelcheckMap = new HashMap<>();
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LabelLayout, defStyleAttr, R.style.LabelLayoutDefault);
try {
horizontalSpacing = (int) a.getDimension(R.styleable.LabelLayout_label_horizontalSpacing, dp2px(8.0f));
verticalSpacing = (int) a.getDimension(R.styleable.LabelLayout_label_verticalSpacing, dp2px(4.0f));
checkboxLayoutId = a.getResourceId(R.styleable.LabelLayout_label_checkboxLayout, R.layout.view_label_common);
enableDivider = a.getBoolean(R.styleable.LabelLayout_label_enableDivider, false);
dividerHeight = a.getDimension(R.styleable.LabelLayout_label_dividerHeight, dp2px(2));
dividerColor = a.getColor(R.styleable.LabelLayout_label_dividerColor, 0xffECECEC);
} finally {
a.recycle();
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (enableDivider) {
if (dividerPaint == null) {
div