Android中实现标签自动换行方法一
public class TagLayout extends LinearLayout {
private List<int[]> children;
public TagLayout(Context context, AttributeSet attrs) {
super(context, attrs);
children = new ArrayList<int[]>();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
measureChildren(widthMeasureSpec, heightMeasureSpec);
final int count = getChildCount(); // tag的数量
int left = 0; // 当前的左边距离
int top = 0; // 当前的上边距离
int totalHeight = 0; // WRAP_CONTENT时控件总高度
int totalWidth = 0; // WRAP_CONTENT时控件总宽度
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) child.getLayoutParams();
if (i == 0) { // 第一行的高度
totalHeight = params.topMargin + child.getMeasuredHeight() + params.bottomMargin;
}
if (left + params.leftMargin + child.getMeasuredWidth() + params.rightMargin > getMeasuredWidth()) { // 换行
left = 0;
top += params.topMargin + child.getMeasuredHeight() + params.bottomMargin; // 每个TextView的高度都一样,随便取一个都行
totalHeight += params.topMargin + child.getMeasuredHeight() + params.bottomMargin;
}
children.add(new int[]{left + params.leftMargin, top + params.topMargin, left + params.leftMargin + child.getMeasuredWidth(), top + params.topMargin + child.getMeasuredHeight()});
left += params.leftMargin + child.getMeasuredWidth() + params.rightMargin;
if (left > totalWidth) { // 当宽度为WRAP_CONTENT时,取宽度最大的一行
totalWidth = left;
}
}
int height = 0;
if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY) {
height = MeasureSpec.getSize(heightMeasureSpec);
} else {
height = totalHeight;
}
int width = 0;
if (MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY) {
width = MeasureSpec.getSize(widthMeasureSpec);
} else {
width = totalWidth;
}
setMeasuredDimension(width, height);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int count = getChildCount();
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
int[] position = children.get(i);
child.layout(position[0], position[1], position[2], position[3]);
}
}
}
使用的话就是
<com.example.test.TagLayout
android:id="@+id/taglayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
TagLayout taglayout = periodView.findViewById(R.id.taglayout);
for (int j = 0;j<2;j++){
View sonItemView = View.inflate(getContext(),R.layout.item_search_flag,null);
taglayout.addView(sonItemView);
}
这种方法就是标签点击事件,如果需要携带数据不是特别方便
方法二是换了一种方式,写了条目点击事件,可以查看下一篇博客
Android实现标签自动换行(二)