Adrian Krebs Adrian Krebs - 5 months ago 20
Android Question

How to save the position of a dragged ImageView in Android?

following situation:

I have a layout with some

ImageView
s on it. The user can drag them around. I also have a button to add some new
ImageView
s. When clicking it you get an overview where you can choose an image. Then the overview activity ends and you return to the fragment.

Now the problem:

Because the
Fragment
is initialized again when returning from the other activity, all positions of the
ImageView
s which I put in place before are lost.

Whats the best way to save the positions of the dragged
ImageView
s? get the margins of each and save them?
I have an SQLite DB running but I think it's an overkill to save the position of each
ImageView
there.

Answer

Well the question is would you like your app to remember the positions even in case of a restart?

If you do, you need to use some sort of persistent storage, such as a database, a File or SharedPreferences.

If not, just cache them in memory, in a HashMap for example.

To get the positions, you could do something like this in your OnDragListener:

public boolean onDrag(View v, DragEvent event) {

    final int action = event.getAction();
    switch(action) {

        // ...

        case DragEvent.ACTION_DROP:
            float x = event.getX;
            float y = event.getY;

            savePosition(x, y);
            break;
    }
}