我正在为Android应用程序实现拖放操作.为了知道drop是否发生在drop target中,我需要知道drop target视图的边界矩形.然后,getRawX/Y()
当我得到ACTION_UP
动作时,我会看到MotionEvent中是否属于这个矩形.
我意识到我可以调用getLeft/Right/Top/Bottom()
放置目标视图,但这些是相对于父容器的.我似乎需要知道"真实"或原始值,以便我可以将它们与MotionEvent中的原始x,y进行比较.
Jef*_*man 59
回答我自己的问题......是的,View.getLocationOnScreen()
做了诀窍.例如,
private boolean isViewContains(View view, int rx, int ry) {
int[] l = new int[2];
view.getLocationOnScreen(l);
int x = l[0];
int y = l[1];
int w = view.getWidth();
int h = view.getHeight();
if (rx < x || rx > x + w || ry < y || ry > y + h) {
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
tbm*_*tbm 31
你也可以在这里使用一个Rect:
private boolean isViewContains(...) {
int[] l = new int[2];
imageView.getLocationOnScreen(l);
Rect rect = new Rect(l[0], l[1], l[0] + imageView.getWidth(), l[1] + imageView.getHeight());
return rect.contains(rx, ry);
}
Run Code Online (Sandbox Code Playgroud)
不那么罗嗦,可能更快,但肯定(IMO)更具可读性.
此代码考虑了所Views
涉及的周长,并且仅true
当拖动View
完全位于放置区域内时才返回.
public boolean containsView(View dropZone, View draggedView){
// Create the Rect for the view where items will be dropped
int[] pointA = new int[2];
dropZone.getLocationOnScreen(pointA);
Rect rectA = new Rect(pointA[0], pointA[1], pointA[0] + dropZone.getWidth(), pointA[1] + dropZone.getHeight());
// Create the Rect for the view been dragged
int[] pointB = new int[2];
draggedView.getLocationOnScreen(pointB);
Rect rectB = new Rect(pointB[0], pointB[1], pointB[0] + draggedView.getWidth(), pointB[1] + draggedView.getHeight());
// Check if the dropzone currently contains the dragged view
return rectA.contains(rectB);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
37700 次 |
最近记录: |