1

I have an ImageView in my layout and I want to move it freely everywhere. I have found some tutorials about moving it with OnTouchListener actions (and I've done my job this way but I don't like it) and some people suggest to use drag and drop api (Android 3+ api) but I can't implement it in the way I want (I mean without target, drag and drop api wants target for the dragged view)

can anyone please provide example? (examples of Drag and Drap API)

Hojjat Imani
  • 333
  • 1
  • 15
Siavash
  • 308
  • 5
  • 17

2 Answers2

0
imageiew.setOnTouchListener(new OnTouchListener() {

    public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
        drag(event, v);
        return true;
    }
});

and then

       public void drag(MotionEvent event, View v)
    {

        RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) v.getLayoutParams();

        switch(event.getAction())
        {
           case MotionEvent.ACTION_MOVE:
           {
             params.topMargin = (int)event.getRawY() - (v.getHeight());
             params.leftMargin = (int)event.getRawX() - (v.getWidth()/2);
             v.setLayoutParams(params);
             break;
           }
           case MotionEvent.ACTION_UP:
           {
             params.topMargin = (int)event.getRawY() - (v.getHeight());
             params.leftMargin = (int)event.getRawX() - (v.getWidth()/2);
             v.setLayoutParams(params);
             break;
           }
           case MotionEvent.ACTION_DOWN:
           {
            v.setLayoutParams(params);
            break;
           }
        }

based oh here

Community
  • 1
  • 1
Payam Asefi
  • 2,677
  • 2
  • 15
  • 26
0

you can try this

img.setOnTouchListener(new OnTouchListener()
{
    PointF DownPT = new PointF(); // Record Mouse Position When Pressed Down
    PointF StartPT = new PointF(); // Record Start Position of 'img'

    @Override
    public boolean onTouch(View v, MotionEvent event)
    {
        int eid = event.getAction();
        switch (eid)
        {
            case MotionEvent.ACTION_MOVE :
                PointF mv = new PointF( event.getX() - DownPT.x, event.getY() - DownPT.y);
                img.setX((int)(StartPT.x+mv.x));
                img.setY((int)(StartPT.y+mv.y));
                StartPT = new PointF( img.getX(), img.getY() );
                break;
            case MotionEvent.ACTION_DOWN :
                DownPT.x = event.getX();
                DownPT.y = event.getY();
                StartPT = new PointF( img.getX(), img.getY() );
                break;
            case MotionEvent.ACTION_UP :
                // Nothing have to do
                break;
            default :
                break;
        }
        return true;
    }
});

I got it from here

Community
  • 1
  • 1
Vasileios Pallas
  • 4,801
  • 4
  • 33
  • 50