Android View 交集不起作用

标签 android intersection android-framelayout rect

我在 Android 中设置了两个非常简单的 View :

screenshot

这是我的代码,用于查看它们是否重叠,但出于某种原因,代码总是返回“不重叠”:

私有(private)FrameLayout firstView; 私有(private) FrameLayout secondView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    firstView = (FrameLayout)findViewById(R.id.numberOne);
    secondView = (FrameLayout)findViewById(R.id.numberTwo);

    if (containsView(secondView, firstView)) {
        Toast.makeText(this, "IS overlapping", Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(this, "IS NOT overlapping", Toast.LENGTH_LONG).show();
    }
}


public boolean containsView(View firstView, View secondView){
    int[] pointA = new int[2];
    firstView.getLocationOnScreen(pointA);
    Rect rectA = new Rect(pointA[0], pointA[1], pointA[0] + firstView.getWidth(), pointA[1] + firstView.getHeight());

    int[] pointB = new int[2];
    secondView.getLocationOnScreen(pointB);
    Rect rectB = new Rect(pointB[0], pointB[1], pointB[0] + secondView.getWidth(), pointB[1] + secondView.getHeight());

    return Rect.intersects(rectA, rectB);
}

最佳答案

您正在检查 View 的位置,然后再进行测量并绘制到屏幕上。调用 firstView.getWidth 可能是 0。您可以通过日志记录来检查它。

添加 TreeObserver 或类似内容:secondView.addOnLayoutChangeListener

顺便说一句,我没有检查你的相交算法是否正确,只是通知你你的错误。

关于Android View 交集不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28841957/

相关文章:

r - 如何获得共享至少 4 列的公共(public)组的最大行集?

C++ : check if two triangles intersect or not

Android:何时/为什么我应该使用 FrameLayout 而不是 Fragment?

android - RelativeLayout 对齐父级 *side* + 边距 *side*

android - LibGDX : Android Game Security

c# - 获取2个圆的交点

android - 从 android 相机解码 NV21 图像,但它的颜色不适合图像

Android布局加载子布局

android - Flutter - 删除 ListView 中项目之间的空间

android - Android SwitchCompat 的垂直对齐方式?