我正在测试我的应用中的拖放功能 我有相对布局,包含两个文本视图 这两个文本视图可以从初始位置拖放到布局中的任何位置
当我拖动文本视图时,它们可以被拖动到屏幕上的任何位置,但如果我将视图放在任何地方,它们都不再可见
我在文本视图上使用了OnTouchListener()和OnDragListener()
帮我解决这个问题
我的活动
public class MainActivity extends Activity
{
private TextView tv1, tv2;
LayoutParams lParams;
private static final String msg = "DRAG EVENT TESTING";
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO: Implement this method
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv1 = (TextView) findViewById(R.id.bigTV);
tv2 = (TextView) findViewById(R.id.smallTv);
tv1.setOnTouchListener(new MyTouchListener());
tv2.setOnTouchListener(new MyTouchListener());
tv1.setOnDragListener(new MyDragListener());
tv2.setOnDragListener(new MyDragListener());
}
private class MyTouchListener implements OnTouchListener
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
ClipData dragData = ClipData.newPlainText("","");
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)
{
switch(event.getAction()){
case DragEvent.ACTION_DRAG_STARTED:
lParams = (RelativeLayout.LayoutParams)v.getLayoutParams();
Log.d(msg, "Action is DragEvent.ACTION_DRAG_STARTED");
break;
case DragEvent.ACTION_DRAG_ENTERED:
Log.d(msg, "Action is DragEvent.ACTION_DRAG_ENTERED");
int x_cord = (int) event.getX();
int y_cord = (int) event.getY();
break;
case DragEvent.ACTION_DRAG_EXITED :
Log.d(msg, "Action is DragEvent.ACTION_DRAG_EXITED");
x_cord = (int) event.getX();
y_cord = (int) event.getY();
lParams.leftMargin = x_cord;
lParams.topMargin = y_cord;
v.setLayoutParams(lParams);
break;
case DragEvent.ACTION_DRAG_LOCATION :
Log.d(msg, "Action is DragEvent.ACTION_DRAG_LOCATION");
x_cord = (int) event.getX();
y_cord = (int) event.getY();
break;
case DragEvent.ACTION_DROP:
Log.d(msg, "ACTION_DROP event");
break;
case DragEvent.ACTION_DRAG_ENDED :
Log.d(msg, "Action is DragEvent.ACTION_DRAG_ENDED");
// Do nothing
break;
default: break;
}
return true;
}
}
}
我的布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<TextView
android:id="@+id/bigTV"
android:layout_height="wrap_content"
android:text="Drag Me"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="wrap_content"/>
<TextView
android:id="@+id/smallTv"
android:layout_height="wrap_content"
android:text="Drag me too but slowly!"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="wrap_content"
android:layout_below="@id/bigTV"/>
</RelativeLayout>
答案 0 :(得分:0)
在ACTION_DROP事件的适当坐标处移动文本视图。