gpt4 book ai didi

android - 在 android 中查找具有给定 x/y 坐标的 View

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:40:07 26 4
gpt4 key购买 nike

是否有可能找到显示在给定绝对 x/y 像素坐标处的 View ?

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

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 是 Resources 的整数数组(在我的例子中,20 个 TextView 排列在一个 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};

为了提高性能,我会考虑使用一个 TextView 数组,然后在每个循环中调用 findViewById()。

最佳答案

一个“解决方案”是遍历父 View 的 subview 并根据您选择的 X 和 Y 坐标检查 getLeft()getTop() 坐标.如果有匹配,你有你的观点。

不过,我想听听其他选择。

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

关于android - 在 android 中查找具有给定 x/y 坐标的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7268358/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com