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;
        }
        }
Was it helpful?

Solution

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;
}

Consider the gridview layout:

enter image description here

Two cells are adjacent if:

  • their index (0~47) are different
  • difference column number <= 1
  • difference row number <= 1

Example:

isAdjacent(6, 18, 12) // true
isAdjacent(6, 18, 19) // true
isAdjacent(6, 18, 24) // true
isAdjacent(6, 18, 17) // false
isAdjacent(6, 18, 18) // false

Notes:

  1. If the first cell index is not 0, use first method with s argument
  2. In this methods, diagonals are considered as adjacent :

Example:

isAdjacent(6, 18, 13) // true
isAdjacent(6, 18, 25) // true
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top