我想在我的测试应用中将拖放功能添加到textview中 主布局包含一个relativelayout(RL1),其中包含另一个relativelayout(RL2) 现在RL2包含一个可以拖放到任何地方的文本视图
但是当我在textview上执行拖动它被拖动但是我放弃它它返回到它的起源位置 请帮帮我
我的主要活动
public class MainActivity extends Activity
{
TextView tv;
LayoutParams lParams;
RelativeLayout layout;
private static final String Tv_TAG =" TV_DRAG";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.mainTextView1);
tv.setTag(Tv_TAG);
tv.setOnTouchListener(new MyTouchListener());
layout = (RelativeLayout) findViewById(R.id. draggableRelativeLayout );
layout.setOnDragListener(new MyDragListener());
}
private class MyTouchListener implements OnTouchListener
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
ClipData.Item item = new ClipData.Item((CharSequence) v.getTag());
String[] mimeTypes ={ClipDescription.MIMETYPE_TEXT_PLAIN};
ClipData dragData = new ClipData(v.getTag().toString(), mimeTypes, item);
View.DragShadowBuilder shdwbldr = new View.DragShadowBuilder(v);
v.startDrag(dragData, shdwbldr, v, 0);
v.setVisibility(View.INVISIBLE);
return true;
}
}
private class MyDragListener implements OnDragListener
{
@Override
public boolean onDrag(View v, DragEvent event)
{
View view = (View) event.getLocalState();
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
lParams =(RelativeLayout.LayoutParams)view.getLayoutParams();
break;
case DragEvent.ACTION_DRAG_ENTERED:
int x_cord = (int) event.getX();
int y_cord = (int) event.getY();
break;
case DragEvent.ACTION_DRAG_EXITED:
x_cord = (int) event.getX();
y_cord = (int) event.getY();
lParams.leftMargin = x_cord;
lParams.topMargin = y_cord;
view.setLayoutParams(lParams);
break;
case DragEvent.ACTION_DROP:
// Dropped, reassign View to ViewGroup
ViewGroup owner = (ViewGroup) view.getParent();
owner.removeView(view);
RelativeLayout container = (RelativeLayout) v;
container.addView(view);
view.setVisibility(View.VISIBLE);
break;
case DragEvent.ACTION_DRAG_ENDED:
break;
default: break;
}
return true;
}
}
}
**我的布局**
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:background="#AE9C9B"
android:id="@+id/ draggableRelativeLayout ">
<RelativeLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:background="@null"
android:id="@+id/mainRelativeLayout1">
<TextView
android:layout_height="wrap_content"
android:text="DRAG ME"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="wrap_content"
android:layout_margin="10dp"
android:id="@+id/mainTextView1"/>
</RelativeLayout>
答案 0 :(得分:2)
您需要为视图设置新坐标:
case DragEvent.ACTION_DROP:
v.setX(event.getX());
v.setY(event.getY());
break;