在android中查找带有给定x/y坐标的视图

phw*_*563 9 android

是否可以找到以给定的绝对x/y像素坐标显示的视图?

编辑:我找到了一个合适的解决方案:

private View findViewByCoord(float x, float y){
    TextView textView = null;
    int[] location = new int[2];
    int width = 0;
    int height = 0;
    for(int reference : cardReference){
        textView = (TextView) findViewById(reference);
        textView.getLocationOnScreen(location);
        width = textView.getWidth();
        height = textView.getHeight();
        if(location[0] <= x && x <= (location[0] + width) && location[1] <= y && y <= (location[1] + height)){
            Log.i("Test", "Card " + textView.getText() + " is pointed");
            return textView;
        }
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

其中cardReference是一个整数到资源的数组(在我的例子中,20个TextViews以4 x 5矩阵排列):

int[] cardReference = new int[]{R.id.card1_1, R.id.card1_2, R.id.card1_3, R.id.card1_4,
                              R.id.card2_1, R.id.card2_2, R.id.card2_3, R.id.card2_4,
                              R.id.card3_1, R.id.card3_2, R.id.card3_3, R.id.card3_4,
                              R.id.card4_1, R.id.card4_2, R.id.card4_3, R.id.card4_4,
                              R.id.card5_1, R.id.card5_2, R.id.card5_3, R.id.card5_4};
Run Code Online (Sandbox Code Playgroud)

为了加快性能,我会考虑使用TextViews数组,然后在每个循环中调用findViewById().

Ric*_*cky 4

一种“解决方案”是循环遍历父视图的子视图,并对照您选择的 X 和 Y 坐标检查getLeft()和坐标。getTop()如果有匹配,您就有自己的看法。

不过我想听听其他选择。

编辑:您还必须根据给出的左侧和顶部坐标计算出视图的高度/宽度,以查看您的坐标是否在该范围内。