Skip to content

Instantly share code, notes, and snippets.

@mrenouf
Created February 9, 2018 19:18
Show Gist options
  • Save mrenouf/9e8c429ef625d472e86974b850576921 to your computer and use it in GitHub Desktop.
Save mrenouf/9e8c429ef625d472e86974b850576921 to your computer and use it in GitHub Desktop.
ViewGroups
package com.example.mrenouf.touchtest;
import android.support.v4.view.ViewCompat;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public final class ViewGroups {
private ViewGroups() {}
private static final ZComparator Z_COMPARATOR = new ZComparator();
private static final List<View> tmpViewList = new ArrayList<>();
public static boolean isTopChildUnder(View child, float x, float y) {
final ViewParent viewParent = child.getParent();
if (!(viewParent instanceof ViewGroup)) {
return true;
}
final ViewGroup parent = (ViewGroup) viewParent;
return getTopChildUnder(parent, x, y) == child;
}
public static View getTopChildUnder(ViewGroup parent, float x, float y) {
// list of siblings ordered by Z, descending (top to bottom)
getTopSortedChildren(parent, tmpViewList);
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = tmpViewList.get(i);
if (child.getVisibility() == View.VISIBLE
&& x >= child.getLeft() && x < child.getRight()
&& y >= child.getTop() && y < child.getBottom()) {
return child;
}
}
// Somehow outside the bounds of all the child views?
return null;
}
private static void getTopSortedChildren(ViewGroup parent, List<View> out) {
out.clear();
final int childCount = parent.getChildCount();
for (int i = childCount - 1; i >= 0; i--) {
out.add(parent.getChildAt(i));
}
Collections.sort(out, Z_COMPARATOR);
}
private static class ZComparator implements Comparator<View> {
@Override
public int compare(View lhs, View rhs) {
final float lz = ViewCompat.getZ(lhs);
final float rz = ViewCompat.getZ(rhs);
if (lz > rz) {
return -1;
} else if (lz < rz) {
return 1;
}
return 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment