繁体   English   中英

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

[英]Find view with given x/y coords in 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;
}

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

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

一个“解决方案”是循环访问父视图的子项,并根据您选择的X和Y坐标检查getLeft()getTop()坐标。 如果匹配,您就有了自己的观点。

我想听听其他的选择。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM