查找视图,在给定的机器人X / Y COORDS [英] Find view with given x/y coords in android

查看:90
本文介绍了查找视图,在给定的机器人X / Y COORDS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能发现显示在一个给定的绝对X / Y像素坐标有何看法?

is it possible to find the View that is displayed at a given absolute x/y pixel coord?

编辑:我找到了一个合适的解决方案,工程巨大的:

I found a suitable Solution that works great:

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是整数,以资源的数组(在我的情况安排在一个4×5矩阵20 TextViews):

Where cardReference is an array of integer to Resources (in my case 20 TextViews arranged in a 4 x 5 Matrix):

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()在每一个循环。

To speed up performance i would consider to use an array of TextViews then call findViewById() in every Loop.

推荐答案

一个解决方案是通过父视图的子循环,并检查 getLeft()共达()坐标下的X和您所选择的Y坐标。如果有一场比赛,你有你的看法。

One 'solution' would be to loop through the parent view's children and check the getLeft() and getTop() coordinates against the X and Y coordinates of your choice. If there is a match, you have your view.

我想听听其他的替代品,但。

I'd like to hear other alternatives though.

编辑:你也不得不在相对于左边和顶部制定出观的高度/宽度太坐标给看看,如果你的坐标是该范围内的

You'd also have to work out the height/width of the view too in relation to the left and top coordinates given to see if your coordinates are within that range.

这篇关于查找视图,在给定的机器人X / Y COORDS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆