How to drag and drop Views in Android RelativeLayout
I made my own drag and drop functions.
I wanted to do it with help RelativeLayout
, but it doesn't seem to work very well. In the beginning, I can tell everyone View
that I want to drag to what position it should be by setting it below View
earlier.
But when I want to drag the View, all the other views below it move as well, because they want to keep the order in which I set them.
But what other layout can I use for this? I have to use this drag and drop function on different screen sizes, so I cannot give them fixed values x
and y
.
source to share
I ran into the same problem a while ago, if you don't want to drag other views (below or above or near your view) along with the dragged view, then use ViewGroup.LayoutParams
instead RelativeLayout.LayoutParams
, the latter is imported if you press Ctrl-Shift-O, so change its manually at first.
Edit: Since you need a description of how I achieved this, here is the actual code
MarginLayoutParams marginParams = new MarginLayoutParams(image.getLayoutParams());
int left = (int) event.getRawX() - (v.getWidth() / 2);
int top = (int) event.getRawY() - (v.getHeight());
marginParams.setMargins(left, top, 0, 0);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(marginParams);
image.setLayoutParams(layoutParams);
I needed to do a lot of research to achieve the same and it took me 2 days to figure out that the MarginLayoutParams thing exists ...
Make sure you have
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
as your import, not RelativeLayout.LayoutParams
.
Also make sure you apply marginparams to your relative positioning. Good luck ...
source to share