2014-03-18 33 views
2

我想知道如何在網格視圖佈局中獲取相鄰項目?目前正在研究可以確定位置相鄰項目的功能。我正在減去柱子的位置,當我在側面和角落時,它顯然變得更加複雜。這可能是很多但我現在可以想到的唯一選擇,有沒有更簡單的方法? 我可以從觸摸事件中獲取位置,矩陣看起來像這樣的位置。Android如何在gridview佈局中查找相鄰的項目

// 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的佈局:

enter image description here

兩個小區相鄰,如果

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

回答

3

嘗試這樣的回答:

  • 它們的索引(0〜47)是不同的
  • 差列號< = 1
  • 差行號< = 1

實施例:

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 

注:

  1. 如果第一小區索引不爲0,則使用第一個方法與s參數
  2. 在這種方法中,對角線被認爲是相鄰的:

實施例:

isAdjacent(6, 18, 13) // true 
isAdjacent(6, 18, 25) // true 
+0

你能在解釋這種細節?? – MashukKhan

+0

我計算'ax'是'a'索引的列數,'ay'是'a'索引的行數,'bx'是'b'索引的列數,''是'b'索引的行數並且如果'a'索引!='b'索引以及列與行號<= 1之間的差(如果'a索引與'b'索引相鄰),則返回true。 – alex

+0

我仍然沒有索引部分。像索引'a'&'b'是什麼,列索引?你會用有問題的矩陣來解釋嗎? – MashukKhan