我正在app中实现拖放视图。我有一个frameLayout和一个视图。我想水平拖动那个视图。我可以拖动该视图但是当我释放它时,视图会消失。这是我的xml文件
<FrameLayout
android:layout_width="match_parent"
android:layout_height="250dip"
android:id="@+id/chart"
android:orientation="vertical"
android:background="#ffffff"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<View
android:id="@+id/drag_line"
android:layout_width="3dp"
android:visibility="invisible"
android:layout_gravity="bottom|center"
android:layout_height="wrap_content"
android:layout_marginBottom="50dp"
android:layout_marginLeft="10dp"
android:background="#FF0000FF" />
这是我的拖放事件处理程序
layout = (FrameLayout) findViewById(R.id.chart);
line = (View) findViewById(R.id.drag_line);
activity.line.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
activity.line.startDrag(data, shadowBuilder, null, 0);
activity.line.setVisibility(View.INVISIBLE);
return true;
} else {
return true;
}
}
});
activity.layout.setOnDragListener(new View.OnDragListener() {
@Override
public boolean onDrag(View view, DragEvent event) {
int currentX = (int) event.getX();
//FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) view.getLayoutParams();
if(event.getAction() == DragEvent.ACTION_DRAG_STARTED){
Log.d(TAG, "STARTED");
y = (int) event.getY();
return true;
}
if(event.getAction() == DragEvent.ACTION_DROP){
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
Log.d(TAG, "Drop");
int x_cord = (int) event.getX();
Log.d(TAG, "Drop X"+x_cord);
Log.d(TAG, "Drop Y"+y);
params.leftMargin = x_cord;
params.topMargin = y;
// line.setY(x_cord);
//layout.removeAllViews();
activity.line.setLayoutParams(params);
activity.line.invalidate();
return true;
}
return true;
}
});
我可以在我的日志中看到我有x和y坐标,但是行消失而不是在那个坐标上。感谢
答案 0 :(得分:0)
您必须像这样设置拖动事件 -
findViewById(R.id.topHalf).setOnDragListener(new ColonyHutDrag());
其中R.id.topHalf是我的Framelayout的id,而ColonyHutDrag是实现onTouchListener的类
public class ColonyHutClick implements OnTouchListener
如果释放的拖动对象没有设置OnDragListener,则无法处理ACTION_DROP,因此您无法将拖动的视图重置为可见。
希望这会对你有所帮助。