Search code examples
androidlayoutadapterdynamic-columns

Android dynamically calculate number of columns


I have a dynamically created list of items which should be displayed in either two or one column depending on the space the containing text needs e.g. if the text is long it will only be one item per row, otherwise two. Obviously they should all be the same size (half the screen size).

As far as I know there's no standard Android view with Adapter that does that. With a GridView you can have multiple columns, but not some rows one column and others two. A TableLayout could stretch views, but also here you have to know how many columns you need per row. Plus it doesn't have an Adapter.

So what I want to know a) is there any control that I'm missing that supports something like this or b) what would be the easiest solution for this problem?

EDIT: the items also contain a CheckBox and I need to keep track of the checked state so I can't just put two items in one view using an Adapter.


Solution

  • As far as I know there is no ready solution for your problem. I haven't yet tried something like this, but I would use a LinearLayout as the list item. Then just create your own Deflater (e.g. CursorAdapter) that deflates the Layout and checks the length. If needed you should be able to add a new View (e.g. TextView) to the LinearLayout.