How to get desktop drag and drop behavior in bin in my own application?

On the Android home screen, you can delete items by dragging them to the trash.

I would like to have similar features in my own application, where I have a view with custom view elements that I want to use for drag and drop.

Is there an easy way to implement this functionality? Or can someone give me pointers that may help me, perhaps with a difficult way to achieve this?

+7
source share
1 answer

I assume that you have a desktop, for example an application, at least a view with the elements you want to drag.

As Austin Mahoney says in his comment, you can link to the Android home desktop with a strong one. But since drag and drop is an easy-to-use feature, you can handle it too.

You need your items for storage, for example. an array . Then view the types of events.

On each ACTION_DOWN you need to check if the user has been hit. For example. if we have circles as elements, we need to fix the current ACTION_DOWN coordinates so that we can check that they are inside the element and get the identifier of the element that the user is going to drag, in accordance with the ACTION_DOWN coordinates.

In ACTION_MOVE, you just need to pass the current x and y coordinates to the element in order to redraw it at the new position.

Well, it's just a drag and drop function. Now you need to check that the element is in a specific sector that you are calling bin. This way you define a rectangle on the screen. in ACTION_MOVE your test so that the element is in this area is all.

Just a sample drag and drop code:

public boolean onTouchEvent(MotionEvent event){ int itemID = 0; int X = (int)event.getX(); int Y = (int)event.getY(); switch(event.getAction()){ case MotionEvent.ACTION_DOWN: for(Items item : dragable_item){ //center coords of the item int centerX = item.getX() + 25; int centerY = item.getY() + 25; //calculate the distance (radius) from touch to item //get item to drag if(distance < 20){ itemId = item.getID(); break; } } break; case MotionEvent.ACTION_MOVE: if(itemID > 0){ Items[itemID-1].setX(X-25); Items[itemID-1].setY(X-25); } break; } } invalidate(); return true; } 

If you want to dig more into the code, see anddev.org - drag and drop.

+1
source

All Articles