Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the homescreen behaviour of drag to bin, in my own application?

On the Android homescreen it's possible to delete the items by dragging them to the bin.

I would like to have similar functionality in my own application, where I have a view with custom view items that I want to be user drag-and-droppable.

Is there a easy way to implement this functionality? Or could somebody give me pointers that can guide me on the possibly difficult way to achieving this?

like image 370
Peterdk Avatar asked Dec 14 '10 16:12

Peterdk


1 Answers

I assume you have a homescreen like application, at least a view with items that you want to drag and drop.

Like Austyn Mahoney says in his comment you can refere to the android open source homescreen code. But since drag and drop is a easy to implement feature you can handle it on your own, too.

You need your items to be stored in e.g. an array. Then go through the event types.

On every ACTION_DOWN you need to check if an item was hit by the user. E.g. if we have circles as items we need to capture the current ACTION_DOWN coordinates so we can check for them to be within the item and obtain the ID of the item that the user is about to drag according to the ACTION_DOWN coordinates.

On ACTION_MOVE you just need to pass the current x and y coordinates to the item to redraw it on the new position.

Well this is just the drag and drop feature. Now you need to test for the item to be in a specific sector you call bin. So you define a rectangle on your screen. in ACTION_MOVE your test the item to be within this area, thats all.

Just some example code for drag and drop:

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 wand to dig more into the code have a look at anddev.org - drag and drop.

like image 187
UpCat Avatar answered Nov 04 '22 16:11

UpCat