我的代码有点问题。我正在开发拖放,用户可以将糖果从罐子拖到特定目标。这个过程很好。但是,当我想将糖果从特定目标拖回罐子时,糖果重叠在一起。
下面的图片显示糖果整齐排列。在我把糖果拖出来之前
然后,在糖果被拖放之后,它看起来像是第二张照片。
根据上图,我将四个糖果拖进罐子里。但糖果是重叠的,这就是为什么你只能在罐子里看到一个甜点。罐子里有四个糖果。
那么,能帮助我吗?我怎样才能安排好我的糖果,这样我把它们放回罐子里后,就会像第一张照片中的糖果一样排列。
这是代码。
case DragEvent.ACTION_DROP:
// // Dropped, reassign View to ViewGroup
ViewGroup owner = (ViewGroup) view.getParent();
Log.i("drop", "Id First :" + view.getId());
Log.i("drop", "Id Second :" + v.getId());
Log.i("value", "Value :" + view.getContentDescription());
owner.removeView(view);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(88, 88);
lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
lp.addRule(RelativeLayout.RIGHT_OF, view.getId());
if(v.getId()==R.id.jaroval)
{
RelativeLayout container = (RelativeLayout) v;
container.addView(view,lp);
value=container.getChildCount();
view.setVisibility(View.VISIBLE);
}
else
{
GridLayout container2 = (GridLayout) v;
container2.setColumnCount(5);
container2.addView(view);
cValue=container2.getChildCount();
value=10-cValue;
view.setVisibility(View.VISIBLE);
}
sound();
break;
答案 0 :(得分:0)
我相信这一行导致了这个问题:
lp.addRule(RelativeLayout.RIGHT_OF, view.getId());
您基本上可以这么说,您当前添加的视图应该在其自身的右侧。相反,您需要提供您添加到jar中的上一个项目的ID。要做到这一点,您只需存储最近添加的项目的ID。
实现此目的的示例代码:
//Create a variable that can be accessed and initialize it as -1
int mostRecentlyAddedView = -1;
//Then in the method you handle drag event
if(mostRecentlyAdddedView == -1){ //This is the very first view, therefore no need to add toRight layout.
// update the variable
mostRecentlyAdddedView = view.getId();
// ... do other things here
} else {
// ... other things
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(88, 88);
lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
lp.addRule(RelativeLayout.RIGHT_OF, mostRecentlyAdddedView);
// ... other things
}