Android From gridview layout index convert into ro

2019-05-17 21:07发布

问题:

If I have index starting from 0, of a position on a grid, how can I turn that into a row, column? I'm getting incorrect results with the following. Fortunately I know how many rows and columns I have and in my case its 11 by 11.

int column = position % columns;

int row = position / columns;

回答1:

// x : horizontal position in range [0; columns-1]
// y : vertical position in range [0; rows-1]

int x = index % columns;
int y = index / columns;
int column = x + 1;
int row = y + 1;

to reverse:

int index = x + y * columns;

or

int index = (column - 1) + (row - 1) * columns;