5 android drag-and-drop imageview ontouchlistener
我有一个想要在用户触摸和移动时在Y轴上重新定位的ImageView.我可以重新定位它但是当我移动它时它会闪烁并且不平滑.它也完全不跟我的手指.有没有办法消除闪烁并改善定位?我正在使用标准的ImageView.
这是我在OnTouch方法中的内容:
imageView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN: {
final float y = event.getY();
// Remember where we started
mLastTouchY = y;
}
break;
case MotionEvent.ACTION_MOVE:
final float y = event.getY();
// Calculate the distance moved
final float dy = y - mLastTouchY;
// Move the object
mPosY += dy;
// Remember this touch position for the next move event
mLastTouchY = y;
imageView.setTranslationY(mPosY);
return true;
}
return false;
}
});
Run Code Online (Sandbox Code Playgroud)
你的图像只想沿着 Y 轴移动,而不是在任何地方移动..如果这是你的问题,这就是答案
2.在DragAndDropBasicActivity类中注释这些行,我在这里是如何做的
public boolean onTouch(View v, MotionEvent event) {
boolean eventConsumed = true;
int x = (int)event.getX();
int y = (int)event.getY();
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN) {
if (v == letterView) {
dragging = true;
eventConsumed = false;
}
} else if (action == MotionEvent.ACTION_UP) {
// if (dragging) {
// emptyLetterView.getHitRect(hitRect);
// if (hitRect.contains(x, y))
// setSameAbsoluteLocation(letterView, emptyLetterView);
// }
dragging = false;
eventConsumed = false;
} else if (action == MotionEvent.ACTION_MOVE) {
if (v != letterView) {
if (dragging) {
setAbsoluteLocationCentered(letterView, x, y);
}
}
}
return eventConsumed;
}
private void setSameAbsoluteLocation(View v1, View v2) {
AbsoluteLayout.LayoutParams alp2 = (AbsoluteLayout.LayoutParams) v2.getLayoutParams();
setAbsoluteLocation(v1, alp2.x, alp2.y);
}
//This method helps the image to keep center of your touch point
private void setAbsoluteLocationCentered(View v, int x, int y) {
setAbsoluteLocation(v, x - v.getWidth() / 2, y - v.getHeight() / 2);
}
// this method help to place the image in exact position when your finger moved up (that is Action UP)
private void setAbsoluteLocation(View v, int x, int y) {
AbsoluteLayout.LayoutParams alp = (AbsoluteLayout.LayoutParams) v.getLayoutParams();
// don't forget to comment this line
//alp.x = x;
alp.y = y;
v.setLayoutParams(alp);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6705 次 |
最近记录: |