2014-10-08 104 views
8

我在另一个尺寸屏幕上绘制视图时遇到问题! 我需要具有View类型两个参数的方法。如果第一个视图重叠在第二个视图上,则返回true,在另一个视图中返回false!检测视图是否重叠

enter image description here

enter image description here

+0

尝试使用不同的布局 – Pr38y 2014-10-08 08:49:05

+0

您使用的是不同的屏幕分辨率不同的布局? – 2014-10-08 08:50:17

+0

我不能改变布局,这是客户的愿望! – smail2133 2014-10-08 08:50:35

回答

14

Berserk感谢你的帮助! 经过一番实验,我写了检测视图重叠与否的方法!

private boolean isViewOverlapping(View firstView, View secondView) { 
     int[] firstPosition = new int[2]; 
     int[] secondPosition = new int[2]; 

     firstView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); 
     firstView.getLocationOnScreen(firstPosition); 
     secondView.getLocationOnScreen(secondPosition); 

     int r = firstView.getMeasuredWidth() + firstPosition[0]; 
     int l = secondPosition[0]; 
     return r >= l && (r != 0 && l != 0); 
    } 
+0

好的工作...... :) – berserk 2014-10-10 08:25:45

+0

这是否涵盖了所有的角落? – 2015-01-12 09:32:22

+0

是的,但我不检查它。这个解决方案对我有好处。试试你。 – smail2133 2015-01-12 09:37:40

3

好像你所要求的代码,你的问题。我发布了我认为可能工作的逻辑:

  1. 创建一个函数,它将两个视图作为参数,并返回一个布尔值。
  2. 现在使用this检查屏幕上两个视图的位置。它会让你知道它们是否重叠。
  3. 根据它返回true或false。
+0

谢谢你的回复!我会试着像你说的那样执行。如果解决方案能够运行良好,我会在这里写代码! – smail2133 2014-10-09 09:09:57

10

您还可以使用Rect.intersect()查找重叠视图。

int[] firstPosition = new int[2]; 
    int[] secondPosition = new int[2]; 

    firstView.getLocationOnScreen(firstPosition); 
    secondView.getLocationOnScreen(secondPosition); 

    // Rect constructor parameters: left, top, right, bottom 
    Rect rectFirstView = new Rect(firstPosition[0], firstPosition[1], 
      firstPosition[0] + firstView.getMeasuredWidth(), firstPosition[1] + firstView.getMeasuredHeight()); 
    Rect rectSecondView = new Rect(secondPosition[0], secondPosition[1], 
      secondPosition[0] + secondView.getMeasuredWidth(), secondPosition[1] + secondView.getMeasuredHeight()); 
    return rectFirstView.intersect(rectSecondView); 
+0

这对我有效,谢谢! – APengue 2016-09-25 04:37:33

+0

这是唯一对我有用的答案。谢谢 – 2017-04-22 16:50:48

1

这与Marcel Derks的答案类似,但是不需要额外的导入。它使用形成Rect.intersect而不创建Rect对象的基本代码。

private boolean isViewOverlapping(View firstView, View secondView) { 
    int[] firstPosition = new int[2]; 
    int[] secondPosition = new int[2]; 

    firstView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); 
    firstView.getLocationOnScreen(firstPosition); 
    secondView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); 
    secondView.getLocationOnScreen(secondPosition); 

    return firstPosition[0] < secondPosition[0] + secondView.getMeasuredWidth() 
      && firstPosition[0] + firstView.getMeasuredWidth() > secondPosition[0] 
      && firstPosition[1] < secondPosition[1] + secondView.getMeasuredHeight() 
      && firstPosition[1] + firstView.getMeasuredHeight() > secondPosition[1]; 
} 

您不需要强制视图测量,但它的好办法做;)