Monday, April 13, 2015

Drag a view with finger in android

Here is a example of  Dragging or moving a view in android,this example will also detect left or right movement of your view and you can perform any thing you want.... on drag left or right..

Create a class which implements OnDragListener

class MyDragListener implements OnDragListener {




@Override
public boolean onDrag(View v, DragEvent event) {

switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
// do nothing
// uiC_imgVMatchingDP.setVisibility(View.INVISIBLE);

endX = event.getX();

positionX = event.getX();


break;
case DragEvent.ACTION_DRAG_ENTERED:

break;

case DragEvent.ACTION_DRAG_EXITED:

break;

case DragEvent.ACTION_DROP:

System.out.println("drop");
try {
if (Math.abs(endX) - Math.abs(positionX) > 150) {
System.out.println("left");
} else if (Math.abs(positionX) - Math.abs(endX) > 150) {
System.out.println("right");
}

} catch (Exception e) {
e.printStackTrace();
}
break;

case DragEvent.ACTION_DRAG_LOCATION:

positionX = event.getX();
// System.out.println("loc drag" + positionX + "end" + endX);
if (Math.abs(endX) - Math.abs(positionX) > 150) {

System.out.println("left");

} else if (Math.abs(positionX) - Math.abs(endX) > 150) {
System.out.println("right");
} else {
System.out.println("150");
}

break;

case DragEvent.ACTION_DRAG_ENDED:




default:
break;

}

return true;
}

}
// end swipe to create



Now set this drag listner to layout which contains your view ,which you want to drag.

Layout.setOnDragListener(new MyDragListener());



NOw create an object of view which you want to drag and set a ontouch listner on that view(the view should be within that layout on which you set onDrag listner).

img_to_drag.setOnTouchListener(new OnTouchListener()
{

@Override
public boolean onTouch(View view, MotionEvent event)
{

     
     
ClipData data = ClipData.newPlainText("", "");
       DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
       view.startDrag(data, shadowBuilder, view, 0);
      

return false;
}
});



its done..!



Now try to drag this view ,it will move with your finger (with in container layout).

enjoy..!





0 comments:

Post a Comment

Don't lose faith when you see others receive answers to their prayers

An elephant and a dog became pregnant at same time. Three months down the line the dog gave birth to six puppies. Six months later the dog...

 

G-Expo Template by Ipietoon Cute Blog Design