Jac*_*1re 5 android drag-and-drop touch
我有一些观点,我喜欢拖延.视图位于LinearLayout内,LinearLayout本身位于scrollview中.
我想得到当前手指的位置(触摸),在我的滚动视图上进行平滑滚动,具体取决于当前拖动的高度.
使用View内置侦听器startDrag长按一下后,我启动了我的draggin
view.startDrag(null, shadowBuilder, view, 0);
Run Code Online (Sandbox Code Playgroud)
我也能够在当前徘徊的视图上获得拖动的相对位置
view.setOnDragListener(new OnDragListener() {
@Override
public boolean onDrag(View v, DragEvent event) {
//get event positions
}
});
Run Code Online (Sandbox Code Playgroud)
但这仅适用于拖动阴影当前所在的视图,而DragEvent仅提供相对位置,而不是原始位置.
我需要的是手指的位置,而阻力发生.不幸的是,所有onTouchEvents都会在拖动时消耗掉.
有人知道我是如何让这个工作的吗?
Ps:我目前使用的一种方式(种类)是通过dragEvent.relativePosition结合视图位置来计算触摸的位置.但是,还有更好的方法吗?
Jac*_*1re 14
好的,因为似乎没有更简单的答案,我将为更多的读者提供我自己的相对简单的解决方案,而不需要手势检测.
首先,您需要接收拖动事件的视图,然后需要拖动事件ifself(或至少x和y坐标).通过获取视图位置和一些简单的添加,您可以获得原始触摸位置.
使用show pointer position developer选项测试此方法以提供正确的数据.
计算方法如下:
/**
* @param item the view that received the drag event
* @param event the event from {@link android.view.View.OnDragListener#onDrag(View, DragEvent)}
* @return the coordinates of the touch on x and y axis relative to the screen
*/
public static Point getTouchPositionFromDragEvent(View item, DragEvent event) {
Rect rItem = new Rect();
item.getGlobalVisibleRect(rItem);
return new Point(rItem.left + Math.round(event.getX()), rItem.top + Math.round(event.getY()));
}
Run Code Online (Sandbox Code Playgroud)
在onDragListener实现中调用此方法:
@Override
public boolean onDrag(View v, DragEvent event) {
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
//etc etc. do some stuff with the drag event
break;
case DragEvent.ACTION_DRAG_LOCATION:
Point touchPosition = getTouchPositionFromDragEvent(v, event);
//do something with the position (a scroll i.e);
break;
default:
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
Addtional:如果您想确定触摸是否在特定视图中,您可以执行以下操作:
public static boolean isTouchInsideOfView(View view, Point touchPosition) {
Rect rScroll = new Rect();
view.getGlobalVisibleRect(rScroll);
return isTouchInsideOfRect(touchPosition, rScroll);
}
public static boolean isTouchInsideOfRect(Point touchPosition, Rect rScroll) {
return touchPosition.x > rScroll.left && touchPosition.x < rScroll.right //within x axis / width
&& touchPosition.y > rScroll.top && touchPosition.y < rScroll.bottom; //withing y axis / height
}
Run Code Online (Sandbox Code Playgroud)
我还基于此解决方案在listview上实现了平滑滚动.因此,用户可以将项目拖出列表,并通过将项目拖动到列表视图的顶部或底部来滚动列表.如果有人对此感兴趣,我可以提供进一步的实施链接.
干杯.
| 归档时间: |
|
| 查看次数: |
6313 次 |
| 最近记录: |