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:
How can i achieve this?
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:
How can i achieve this?
You can approach the problem in two main ways:
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.
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.