I have a view, and I want to move it with finger. I wanted to get the xDelta and yDelta and just translate the matrix of the view (not image view, any view, RelativeLayout for example). I am wondering how to do that:
Can't I manipulate the matrix of any view directly through onDraw? I tried something like this:
@Override
protected void onDraw(Canvas canvas) {
if (getDx() != 0 && getDy() != 0) {
m = canvas.getMatrix();
m.postTranslate(dx, dy);
canvas.setMatrix(m);
}
super.onDraw(canvas);
}
But it seems that I am doing it wrong.
If you want to implement drag gesture then you can use onTouchListener and in its MotionEvent.ACTION_MOVE set padding using setPadding to that view.
Here is the sample code:
case MotionEvent.ACTION_MOVE:
yourView.setPadding((int)event.getRawX(), (int)event.getRawY(), 0, 0);
Sample for onTouchListener :-
OnTouchListener drag= new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction() & MotionEvent.ACTION_MASK){
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_POINTER_DOWN:
break;
case MotionEvent.ACTION_MOVE:
img.setPadding((int)event.getRawX(), (int)event.getRawY(), 0, 0);
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_POINTER_UP:
break;
} return true;
}
};
You need to create the dragging image at run time and have to adjust its position. In this sample code I have not adjusted the position so the dragged image is not created at the position of touch. You also need to consider the height and width of the image to be dragged.
Hope it helps !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With