Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving any RelativeLayout with finger (without changing layout params)

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:

  1. Overriding RelativeLayout's onDraw and apply translation matrix there. Is that possible?
  2. I am currently doing it with applying animation on each onTouch event. The animation is with duration 0 and the start/end of x/y is the same (setFillAfter = true). It just puts the view where I want. But isn't that too expensive?

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.

like image 464
Danail Avatar asked Dec 26 '22 15:12

Danail


1 Answers

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 !

like image 80
Code Word Avatar answered Mar 17 '23 03:03

Code Word