3

I am trying to achieve a gridview with a different number of items in each row, depending on the width of each item. I want it to look like the one on the Medium app, as shown below:

Medium

How can i achieve this?

Alex Kombo
  • 3,256
  • 8
  • 34
  • 67

1 Answers1

1

You can approach the problem in two main ways:

  1. Use ScrollView with a Linear- or RelativeLayout inside. Then you would add the items in your code, measuring each and putting them into new rows when required. This will require some logic to be created, but is achievable. The ScrollView will take care of the scrolling in case the contents exceed the screen height. The problem with this solution is that you will not have a recycling mechanism, which can lead to problems with memory when the list gets long.

  2. Use RecyclerView! :-D One of the awesome features of the RecyclerView is the fact that while providing the standard Adapter-based concept of the list of items, it also allows you to implement a custom LayoutManager. Create your own implementation of LayoutManager which positions the items based on their measured with and you are done, the RecyclerView will take care of scrolling and recycling the items for you! :-D This will take some getting used to, especially if you have no experience with RecyclerView, but the whole thing should take no more than several hours and is, in my humble opinion, really worth it.

You are free to choose either, but the second approach is more modern and, in general, easier to implement. In general, you should learn to use the RecyclerView, it helps a lot and is quicker to implement than the good old List- and GridViews, once you get the hang of it.

Kelevandos
  • 7,024
  • 2
  • 29
  • 46
  • I had considered using a `RecyclerView` but the problem is using it inside a `ScrollView` which doesnt really work well. – Alex Kombo Jan 15 '16 at 08:10
  • And why do you need a `ScrollView`? – Kelevandos Jan 15 '16 at 08:10
  • I have other items on the same layout, and the above `GridView` will be the last thing on the layout. – Alex Kombo Jan 15 '16 at 08:13
  • Well, it is possible to have a RecyclerView in a Scrollview, you need to set its android_height and android_minHeight params to defined values. However, you should not do this in most cases. See [this](http://stackoverflow.com/questions/27083091/recyclerview-inside-scrollview-is-not-working) question's first answer. – Kelevandos Jan 15 '16 at 08:20
  • Just try setting it as late as possible, once you have the number of items and the height of the inflated Recycler with those items and it should be fine. As long as you do not plan on adding items to it dynamically, that is ;-) – Kelevandos Jan 15 '16 at 08:28