在过去的几天里,我一直在努力使用这个程序。我面临的问题是关于排除另一个视图的视图的放置事件。该程序应该做的是,单击一个按钮,创建尽可能多的 ImageButtons,并且它们都可以拖放到屏幕上的任何位置。但是,他创建了第一个视图并创建了第二个,但是当我拖动第二个 ImageButton 时,创建的第一个已从屏幕中删除。
这是XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/relative_main"
tools:context=".WhyItActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="add button"
android:onClick="addButton" />
</RelativeLayout>
下面是负责的java活动
public class WhyItActivity extends Activity {
private RelativeLayout relative;
private LayoutParams params;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_why_it);
params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
relative = (RelativeLayout)findViewById(R.id.relative_main);
// all the screen be a dropping area
relative.setOnDragListener(new View.OnDragListener() {
@Override
public boolean onDrag(View view, DragEvent event) {
View dragView = (View) event.getLocalState();
RelativeLayout layout = (RelativeLayout) view;
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
break;
case DragEvent.ACTION_DRAG_ENTERED:
break;
case DragEvent.ACTION_DRAG_EXITED:
break;
case DragEvent.ACTION_DROP:
int right = (int)event.getX();
int top = (int)event.getY();
params.setMargins(right, top, 0, 0);
layout.removeView(dragView);
layout.addView(dragView, params);
// set back the visibility
dragView.setVisibility(View.VISIBLE);
break;
case DragEvent.ACTION_DRAG_ENDED:
break;
default:
break;
}
return true;
}
});
}
/** OnClick */
public void addButton(View v){
// params for centralizing the image button
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
// new object
ImageButton imgBtn = new ImageButton(this);
imgBtn.setImageDrawable(getResources().getDrawable(R.drawable.ic_launcher));
relative.addView(imgBtn, params);
// letting the view be dragged around the screen
imgBtn.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
ClipData data = ClipData.newPlainText("", "");
DragShadowBuilder builder = new View.DragShadowBuilder(view);
view.startDrag(data, builder, view, 0);
// let the view be invisible while dragging the object
view.setVisibility(View.INVISIBLE);
return true;
}
});
}
所以,问题是......我在哪里搞砸?我创建了一个新对象,如果它只是屏幕上的一个视图,它会工作得很好。
感谢您到目前为止的阅读,并且可能能够提供帮助。