用textview包装布局

Ses*_*nay 17 layout android

我的布局看起来像这样:

<RelativeLayout>
<!--aligned parent top-->
</<RelativeLayout>
<FlowLayout>
<!--Should fill remaining space-->
</FlowLayout>
<RelativeLayout>
<!--aligned parent bottom-->
</<RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

我使用FlowLayout显示文本视图列表(它可能包含10-15个文本视图).因此,基于可用的空屏幕空间,我想显示文本视图的数量.例如,如果要在那里显示15个文本视图,并且在大屏幕中有10个文本视图的空间,我想显示9个文本视图并在最后一个文本视图中显示"+6".在一个小屏幕空间可能只有5个textviews可用,因为我想在最后一个textview中显示4个带有"+11"的文本视图.为了清楚理解,这是截图.如您所见,要显示的实际文本视图数为5.但显示的是2,并且添加了+3.同样,根据可用的屏幕空间,我想在布局中添加多个textview.

如何以编程方式实现?

在此输入图像描述

Cod*_*ury 9

尝试以编程方式将TextViews添加到for循环中的linearLayout,其中在添加每个textView之后,获得剩余宽度可用(可以使用[ScreenWidth-(添加的textviews宽度的总和+ [no textof*of margin/padding for each])计算]*)

如果width小于某个最小值(假设每个textview最少需要100px),则打破循环并添加计数指示符文本.

我可以想到下面的代码,它可能不准确但只是为了告诉你我在想什么

int screenWidth = getScreenWidth();
    int currentWidth=0;
    int minimumWidthForAChildWithOffset = 100;//offset should include width of indicator 
    int childCount = 10;
    int paddingForEachChild = 15;
    for (int i = 0; i <childCount; i++) {
        TextView label= getChildView();
        parent.addView(label, i);
        currentWidth += parent.getChildAt(i).getWidth() + paddingForEachChild;
        if(i!=childCount-1/*ignore if this is the last item*/ && screenWidth-currentWidth<=minimumWidthForAChildWithOffset){
            //add indicator label to layout here
            break;
        }
    }
Run Code Online (Sandbox Code Playgroud)


yed*_*yak 2

尝试在循环中添加文本视图,将每个文本视图单独添加到新的 OnPreDrawListener 中。每添加一个后,检查是否超出了行上的空间,如果超出则将其删除并添加计数器。如果仍然超过该行,则再删除一个并增加计数器。

关键是在单独的 OnPreDrawListener 中测试每个,因此这一切都发生在视图显示之前,但在视图计算其布局和大小之后。