【问题标题】:Android how to find adjacent items in gridview layoutAndroid如何在gridview布局中查找相邻项目
【发布时间】:2014-03-18 20:38:43
【问题描述】:

我想知道如何在网格视图布局中获取相邻项目?目前正在开发可以从位置确定相邻项目的功能。我将位置减去列,当我在边角时,它显然会变得更加复杂。可能很多,但我现在能想到的唯一选择,有没有更简单的方法? 我可以从触摸事件中获取位置,并且带有位置的矩阵看起来像这样。

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

【问题讨论】:

    标签: android android-layout gridview adjacency-matrix


    【解决方案1】:

    试试这个:

    // 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布局:

    两个单元格相邻,如果:

    • 它们的索引 (0~47) 不同
    • 不同的列号
    • 不同的行号

    例子:

    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
    

    【讨论】:

    • 你能详细解释一下吗?
    • 我计算axa索引的列数,aya索引的行数,bxb索引的列数,by b 索引的行号,如果 a 索引 != b 索引并且列号和行号之间的差异 a 索引与 b 索引相邻),则返回 true。跨度>
    • 我仍然没有得到索引部分。像索引a & b 是什么,列索引??你能在给出的矩阵中解释一下吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    • 1970-01-01
    • 1970-01-01
    • 2022-06-28
    • 1970-01-01
    相关资源
    最近更新 更多