How can I drag and drop Views within Android RelativeLayout

寵の児 提交于 2019-12-09 19:00:47

问题


I made my own drag and drop functionality.

I wanted to do this with a RelativeLayout, but this seems not to work very well. At the beginning i can tell each View I want to drag on which position it should be by setting it below the View before.

But when I want to drag a View, all the other Views beneath it are moved too, 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 functionality on different screen sizes, so I cant' give them fixed x and y values.


回答1:


I faced the same trouble a while ago, if you do not want to drag other views (either below or above or beside your view) along with the view being dragged, then use ViewGroup.LayoutParams instead of RelativeLayout.LayoutParams, the latter is imported if you hit Ctrl-Shift-O, so change it manually to the former.

Edit: Since you wanted the description of how I achieved that, 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 had to do a lot of research to achieve the same and it took me 2 days to figure out that a thing called MarginLayoutParams exists...

Make sure that you have

import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;

as your imports and not RelativeLayout.LayoutParams.

Also make sure that you cast marginparams to your relative layout Best of luck...



来源:https://stackoverflow.com/questions/10073304/how-can-i-drag-and-drop-views-within-android-relativelayout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!