我想知道如何在网格视图布局中获取相邻项目?目前正致力于可以确定该位置的相邻项目的功能。我减去了位置减去了柱子,当我在两侧和角落时,它显然变得更加复杂。它可能是很多但我能想到的唯一选择,是否有更简单的方法? 我可以从触摸事件中获取位置,矩阵看起来像是位置。
1 2 3 4
5 6 7 8
9 10 11 12
从下面回答
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;
}
}
答案 0 :(得分:3)
试试这个:
// 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;
}
考虑gridview布局:
如果出现以下两个单元格相邻:
示例:
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
注意:
s
参数的第一个方法示例:
isAdjacent(6, 18, 13) // true
isAdjacent(6, 18, 25) // true