views:

596

answers:

3

I would like to produce an android user interface which allows the user to move added components/widgets around the screen by selecting them and then dragging them around.

Is this possible using the standard android apis?

A: 

To some degree. It depends on what degree of freedom you want to give the user. One solution that comes to mind is a TableLayout with predefined cells. A user can then tap and drag components. When dragging a component you'll just want to draw an image of it under the user's finger, but when they release, remove the component from it's previous parent and add it to the new parent using the ViewGroup add/remove methods.

While you can programmatically shift Views around, it would be difficult/impossible to switch layouts on the fly as far as I can see.

Soonil
+1  A: 

Yes. It depends what you are trying to achieve.

It can be done using the standard APIs, but this functionality is not part of the standard APIs. That is, there is no "widget.DragOverHere()" method unless you write one.

That said, it would not be terribly complicated to do. At a minimum, you would need to write a custom subclass of View and implement two methods: onDraw(Canvas c) and onTouch(MotionEvent e). A rough sketch:

class MyView extends View {

int x, y;  //the x-y coordinates of the icon (top-left corner)
Bitmap bitmap; //the icon you are dragging around

onDraw(Canvas c) {
  canvas.drawBitmap(x, y, bitmap);
}

onTouch(MotionEvent e) {
  switch(e.getAction()) {
  case MotionEvent.ACTION_DOWN:
    //maybe use a different bitmap to indicate 'selected'
    break;
  case MotionEvent.ACTION_MOVE:
    x = (int)e.getX();
    y = (int)e.getY();
    break;
  case MotionEvent.ACTION_UP:
    //switch back to 'unselected' bitmap
    break;
  }
  invalidate(); //redraw the view
}
}
allclaws
A: 

The way I have done this is to have an absolute layout and then just update the object position as it is dragged. You have to implement dragging yourself. If the widgets have a natural order (a toolbar where you want to be able to drag buttons around) you can stack an absolute layout on top of the toolbar and when the drag starts, you add it to the absolute layout and when it finishes, you add it back to the original layout in the new position.

hacken