【问题标题】:GridLayout - find child by coordinates x, yGridLayout - 通过坐标 x, y 查找子级
【发布时间】:2016-08-17 14:10:33
【问题描述】:

我有一个非常大的 GridLayout(128x128 单元格)。我需要检测在每个子项目上的滑动。目前我在 GridLayout 上使用 OnTouchListener,这段代码用来检测用户滑过哪个项目。

@Override
public boolean onTouch(View view, MotionEvent event)
{
    int x = (int) event.getX();
    int y = (int) event.getY();

    int count = glImage.getChildCount();
    for(int i = 0; i < count; i++)
    {
        CircleImageView ivPart = (CircleImageView) glImage.getChildAt(i);

        if(isPointWithin(x, y, ivPart.getLeft(), ivPart.getRight(), ivPart.getTop(), ivPart.getBottom()))
        {
            // some code
        }
    }

    return true;
}

private static boolean isPointWithin(int x, int y, int x1, int x2, int y1, int y2)
{
    return (x <= x2 && x >= x1 && y <= y2 && y >= y1);
}

此代码有效,但速度很慢,因为每次滑动位置更改都会导致迭代循环 128^2 次。有没有更好的方法来获取 GridLayout 中孩子的位置?

我也尝试使用 onTouchListener for child,但 onTouch() 仅在滑动时在 start-item 上调用。

【问题讨论】:

  • for 循环本身不应该很慢,它很慢,因为您在每次迭代时都为您的 CircleImageViews 提供了新的引用。生成网格时,尝试将它们存储在数组或列表中。之后我确信 for 迭代会很好。

标签: android touch swipe gesture


【解决方案1】:

您可以尝试将视图的所有位置提前计算到数组中,然后对行(y)和列(x)使用二进制搜索,如果孩子的大小不可变,它将起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-28
    • 2012-12-16
    • 1970-01-01
    • 2015-12-13
    • 2016-12-26
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    相关资源
    最近更新 更多