2011-09-01 51 views
9

是否有可能找到显示在给定的绝对x/y像素坐标上的视图?在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是整数的阵列,以资源(在我的情况排列成4×5矩阵20个TextViews):

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()。

回答

4

一个“解决方案”是循环浏览父视图的子项并根据您选择的X和Y坐标检查getLeft()getTop()坐标。如果有一场比赛,你有你的看法。

虽然我想听听其他的选择。

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