MAXGEN - 3 months ago 25

Android Question

I was wondering on how you can get adjacent item within grid view layout? Currently working on function that can determine the adjacent items from the position. I'm subtracting the position minus the columns and it obviously gets more complicated when I'm on the sides and corners. It might be to much but the only option i can think of now, is there easier way?

I can get postions from an touch event and the matrix looks like this with postions.

`1 2 3 4`

5 6 7 8

9 10 11 12

Answer from below

`boolean isedgeitem(int position)`

{

int row = position % 11;

int column = position / 11;

int numberedges = 0;

for (int rowOffset = -1; rowOffset <= 1; rowOffset++)

{

final int actRow = row + rowOffset;

for (int columnOffset = -1; columnOffset <= 1; columnOffset++)

{

final int actColumn = column + columnOffset;

if (actRow >= 0 && actRow < 11 && actColumn >= 0 && actColumn < 11)

{

numberedges++;

}

}

}

if (numberedges < 8)

{

return true;

}

else

{

return false;

}

}

Answer

Try this:

```
// x = number of columns
// s = index start
// a = index of a
// b = index of b
// if your index doesn't starts at 0
public static boolean isAdjacent(int x, int s, int a, int b) {
int ax = (a - s) % x, ay = (a - s) / x, bx = (b - s) % x, by = (b - s) / x;
return a != b && Math.abs(ax - bx) <= 1 && Math.abs(ay - by) <= 1;
}
// if your index starts at 0
public static boolean isAdjacent(int x, int a, int b) {
int ax = a % x, ay = a / x, bx = b % x, by = b / x;
return a != b && Math.abs(ax - bx) <= 1 && Math.abs(ay - by) <= 1;
}
```