gpt4 book ai didi

Android - 像标签一样堆叠项目

转载 作者:行者123 更新时间:2023-11-29 17:36:21 26 4
gpt4 key购买 nike

我有什么:

enter image description here

我想做什么:

enter image description here

每当我添加项目时,我都希望将它放在之前的项目旁边。如果一个元素在屏幕的末尾:我希望它被放置在下一行。
CSS 中类似于 float: left

最佳答案

如果你希望你的标签容器最终滚动,那么使用 RecyclerViewGridLayoutManager并调用它 setSpanCount(3)。不要忘记将其方向设置为 VERTICAL

如果您永远不需要滚动项目,那么只需使用 GridLayout

编辑:

我已经按照您想要的方式整理了粗略的示例。您可能还需要考虑边距和填充,但这应该是您如何做到这一点的基本思路。

public class TagLayout extends ViewGroup {

public TagLayout(Context context) {
super(context);
}

public TagLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}

public TagLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}

public TagLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
int maxWidth = getMeasuredWidth();
int count = getChildCount();

int tagLeft = left,
tagTop = top,
tagRight = 0,
tagBottom = 0;

for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {

tagRight = tagLeft + child.getMeasuredWidth();
tagBottom = tagTop + child.getMeasuredHeight();

if (tagRight > maxWidth) {
tagLeft = left;
tagRight = left + child.getMeasuredWidth();
tagTop = tagBottom;
tagBottom += child.getMeasuredHeight();
}
child.layout(tagLeft, tagTop, tagRight, tagBottom);
tagLeft = left;
}

}
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

int width = 0;
int height = 0;
int count = getChildCount();
int maxWidth = MeasureSpec.getSize(widthMeasureSpec);

for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
measureChild(child, widthMeasureSpec, heightMeasureSpec);
width += child.getMeasuredWidth();
if (height == 0) {
height += child.getMeasuredHeight();
}
if (width <= maxWidth) {
continue;
} else {
width = 0;
height += child.getMeasuredHeight();
}
}

}
setMeasuredDimension(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
}

}

关于Android - 像标签一样堆叠项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30372929/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com