我做了一个拖放系统,但当我插入物品时,看起来重力是顶部,当插入新的时,它们会保持在彼此的顶部,我如何放下我放开手指的地方?
这些项目在列表中,我这样得到它们:
public void criarListagem(List<croquiA> cro) {
CroquiAdapter adapter = new CroquiAdapter(cro, this);
listView.setAdapter(adapter);
listView.setDivider(null);
listView.setOnItemLongClickListener((parent, view, position, id) -> {
arrayClass.p = arrayClass.pistasIds[position];
ClipData data = ClipData.newPlainText("simple_text", "text");
View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
view.startDrag(data, shadowBuilder, view, 0);
view.setVisibility(View.VISIBLE);
newClick(arrayClass.p, l);
if(l != 0){
findViewById(R.id.container).setOnDragListener(new MyOnDragListener());
}
return false;
});
MyOnDragListener:
class MyOnDragListener implements View.OnDragListener{
public MyOnDragListener(){
super();
}
@Override
public boolean onDrag(View v, DragEvent event) {
int action = event.getAction();
switch (action){
case DragEvent.ACTION_DRAG_STARTED:
if(event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)){
return true;
}else{
return false;
}
case DragEvent.ACTION_DRAG_ENTERED:
break;
case DragEvent.ACTION_DRAG_LOCATION:
break;
case DragEvent.ACTION_DRAG_EXITED:
break;
case DragEvent.ACTION_DROP:
View view = (View) event.getLocalState();
RelativeLayout container = (RelativeLayout) v;
//Here I copy to the view and add an ImageView
//instead of remove because it is an adapter, so it is
//not possible to remove it
ImageView oldView = (ImageView) view;
ImageView newView = new ImageView(getApplicationContext());
newView.setImageBitmap(((BitmapDrawable) oldView.getDrawable()).getBitmap());
container.addView(newView);
break;
case DragEvent.ACTION_DRAG_ENDED:
break;
}
return true;
}
当我放下它时看起来像这样:
因为我做了2滴,意识到一张图像在另一张图像的顶部,并且它们不是在我放开手指的地方创建的
答案 0 :(得分:1)
在MyOnDragListener中,您需要指定位置,将新视图放入布局的位置。请尝试以下操作:更改此行
container.addView(newView);
进入
RelativeLayout.LayoutParams params;
params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
params.leftMargin = (int) event.getX() - oldView.getWidth()/2;
params.topMargin = (int) event.getY() - oldView.getHeight()/2;
container.addView(newView, params);