我正在制作可以包含一些 subview 的CustomLayout
。这些 subview 可能彼此重叠。这些 subview 的变换矩阵可以通过 setRotation
setScale
等修改。
我们如何通过本地位置(x,y)获取子项?:
class CustomLayout extends ViewGroup {
public View getChildByLocation(int x, int y) {
// HOW TO IMPLEMENT THIS
}
}
据我所知,到目前为止 ViewGroup
允许我们 getChildAt(index)
这样我就可以循环遍历它的 subview 来找出我需要的 View 。但它太复杂了,我想要一个正式的方法来通过位置(x,y)获取 child 。
提前谢谢您!
最佳答案
使用下面的 Utils 类。只需要调用 1 次方法
无需对布局进行子类化。从主线程调用该方法,它也支持平移/旋转/缩放。
// return null if no child at the position is found
View outputView = Utils.findChildByPosition(theParentViewGroup, x, y)
Utils 类的完整源代码:
public final class Utils {
/**
* find child View in a ViewGroup by its position (x, y)
*
* @param parent the viewgourp
* @param x the x position in parent
* @param y the y position in parent
* @return null if not found
*/
public static View findChildByPosition(ViewGroup parent, float x, float y) {
int count = parent.getChildCount();
for (int i = count - 1; i >= 0; i--) {
View child = parent.getChildAt(i);
if (child.getVisibility() == View.VISIBLE) {
if (isPositionInChildView(parent, child, x, y)) {
return child;
}
}
}
return null;
}
private static boolean isPositionInChildView(ViewGroup parent, View child, float x, float y) {
sPoint[0] = x + parent.getScrollX() - child.getLeft();
sPoint[1] = y + parent.getScrollY() - child.getTop();
Matrix childMatrix = child.getMatrix();
if (!childMatrix.isIdentity()) {
childMatrix.invert(sInvMatrix);
sInvMatrix.mapPoints(sPoint);
}
x = sPoint[0];
y = sPoint[1];
return x >= 0 && y >= 0 && x < child.getWidth() && y < child.getHeight();
}
private static Matrix sInvMatrix = new Matrix();
private static float[] sPoint = new float[2];
}
关于java - ViewGroup 如何按位置(x,y)获取 subview ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41690473/