Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wrap a layout with textviews

Tags:

android

layout

I have a layout that looks like this:

<RelativeLayout>
<!--aligned parent top-->
</<RelativeLayout>
<FlowLayout>
<!--Should fill remaining space-->
</FlowLayout>
<RelativeLayout>
<!--aligned parent bottom-->
</<RelativeLayout>

I used FlowLayout to show a list of textviews(It may contain 10-15 textviews). So, based on available empty screen space, I want to show number of textviews. For example, if there are 15 textviews to be shown there and there is space for 10 textviews in a large screen, I want to show 9 textviews and show "+6" in the last textview. In a small screen space may be available only for 5 textviews, in that i want to show 4 textviews with "+11" in the last textview. For clear understanding, here is the screenshot. As you can see, actual number of textviews to be displayed are 5. but 2 are displayed, and +3 is added. Similarly, based on screen space available, I want to add number of textviews in the layout.

How can this be achieved programmatically?

enter image description here

like image 980
Seshu Vinay Avatar asked Dec 01 '15 05:12

Seshu Vinay


2 Answers

Try programmatically adding TextViews to a linearLayout in a for loop in which after adding each textView, get remaining width available (Can be calculated using [ScreenWidth-(sum of added textviews width + [no.of textviews * margin/padding for each])]*)

If width is less than a certain minimum (say you need 100px minimum for each textview) then break the loop and add the count indicator text.

I can think of below code, it might not be precise but just to show you what Im thinking of

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;
        }
    }
like image 63
CodeFury Avatar answered Sep 29 '22 01:09

CodeFury


Try adding the textviews in a loop, adding each one separately in a new OnPreDrawListener. After each one is added, check if it exceeds the space on the row, and if so remove it and add the counter. If it still exceeds the row, remove one more and increase the counter.

The key is to test each in a separate OnPreDrawListener, so it all happens before the view is shown, but after the view has had its layout and size calculated.

like image 42
yedidyak Avatar answered Sep 28 '22 23:09

yedidyak