Friday, 12 October 2018

Centralise last row of GridView

I have a dynamic GridView which is supposed to display data fetched from the server. The length of this data is variable. I have set android:numColumns="4". Now, if the length of the data is divisible by 4, then my layout looks like:

Screenshot for Number of cells divisible by 4

which is how it's supposed to be. But, if the length of the data is not divisible by 4 but is even (of the form 4k+2), then the layout looks like:

Screenshot for Number of cells of the form 4k+2

I had a look at this StackOverflow question and a lot of people suggested insertion of dummy elements to trick the GridView into leaving empty space. This seemed like a hack but I did achieve the layout I wanted:

Screenshot for Number of cells of the form 4k+2, centered

Now, the problem arises when the length of the data is odd. The layout I get by default looks like:

Screenshot for Number of cells odd

What I would like is to get something like this:

Screenshot for Number of cells odd

Notice that the previous workaround will not work here since there isn't a complete extra cell where a dummy could be inserted.

One solution I could come up with was to change the number of columns to 7 and replace every alternate cell with a dummy node, except for the last row where the first cell is a dummy too. This gave me something like:

Screenshot for Number of cells odd, with 7 columns

Even after getting rid of the horizontalSpacing, these cells are too far apart, and the code readability has been severely compromised. Now, I am not looking for workarounds where the size of dummy cells could be reduced. Instead, I would like to get rid of the dummy cells as well because that's not an efficient way to do this, in my opinion.

I have gone through the documentation for GridView where I could not find anything related to my problem. I have also looked at this and this StackOverflow questions in addition to the one linked above but none of them seem to have a valid answer. I also found this GitHub repository where the author claims to have fixed this, but I could not reproduce it.

I would be happy to provide code snippets from my project, but I don't think they'll be useful because:

  • I'm looking for a generic solution, not specific to my particular case.
  • My project is not as simple as placing alphabets in a GridView and it includes a lot of extra details which are not relevant to this problem and hence have been removed in order to avoid confusion.


from Centralise last row of GridView

No comments:

Post a Comment