嗨,我现在正在开发一个Android应用程序,这是一个简单的模因制作工具。为了向画布添加元素(图片),我使用了一个像这样的自定义视图作为画布...
<RelativeLayout>
<CustomScrollView....
<LinearLayout....
<CanvasView.....
</CanvasView>
</LinearLayout>
</CustomScrollView>
</RelativeLayout>
所有元素都将添加到CanvasView中,并且运行良好。当我向CanvasView中的元素添加拖放时,它有一个问题,很难在垂直方向上悬垂元素(Horizontal很好),我认为这是因为CustomScrollView,所以我将其删除,并且效果很好。
但是CanvasView过去比屏幕尺寸的高度长,所以我需要CanvasView可以上下滚动,只是我认为ScrollView对此有好处,如何解决关于“触摸事件”之间的冲突的问题ScrollView和CanvasView?
最佳答案
我已经尝试了一段时间并在这里找到解决方案:
public class CanvasContainerScrollView extends ScrollView {
public boolean enableScrollView = true;
public CanvasContainerScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
@Override
public boolean onTouchEvent(MotionEvent event) {
android.util.Log.v ("scrollview", "touched");
if (enableScrollView) {
return super.onTouchEvent(event);
}
return false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (enableScrollView) {
return super.onInterceptTouchEvent(event);
}
return false;
}
}
设置enableScrollView将启用滚动或老虎钳。在CanvasView onTouchEvent-
@Override
public boolean onTouchEvent(MotionEvent ev) {
final int action = ev.getAction();
android.util.Log.v("canvasView", "touched");
switch (action) {
case MotionEvent.ACTION_DOWN: {
final float x = ev.getX();
final float y = ev.getY();
int i = 2;
for (i = goList.size() - 1; i >= 0; --i) {
if (currentObjectLayer == -1 && goList.get(i).inHitArea(x, y)) {
parent.enableScrollView = false;
if (currentObjectLayer != -1) {
continue;
}
goList.get(i).selected();
currentObjectLayer = i;
// break;
} else {
// if (goList.get(i).inHitArea(x, y)) {
// parent.enableScrollView = false;
// } else {
// parent.enableScrollView = true;
// }
goList.get(i).unselected();
}
}
if (currentObjectLayer == -1) {
parent.enableScrollView = true;
}
// Remember where we started
lastTouchX = x;
lastTouchY = y;
break;
}
case MotionEvent.ACTION_MOVE: {
final float x = ev.getX();
final float y = ev.getY();
// Calculate the distance moved
final float dx = x - lastTouchX;
final float dy = y - lastTouchY;
// Move the object
posX += dx;
posY += dy;
// Remember this touch position for the next move event
lastTouchX = x;
lastTouchY = y;
// android.util.Log.v("image", "dx=" + dx + ":dy=" + dy);
if (currentObjectLayer != -1) {
goList.get(currentObjectLayer).left += dx;
goList.get(currentObjectLayer).top += dy;
goList.get(currentObjectLayer).dx = dx;
goList.get(currentObjectLayer).dy = dy;
}
// Invalidate to request a redraw
invalidate();
break;
}
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
// goList.get(currentObjectLayer).objectType = 0;
currentObjectLayer = -1;
parent.enableScrollView = true;
break;
}
invalidate();
return true;
}