0
我正在測試拖放功能在我的應用程序 我有相對佈局,其中包含兩個文本視圖 這兩個文本視圖可以從他們的初始位置拖放到任何地方在佈局拖放完成後拖放視圖不可見
當我拖累他們能夠在屏幕上任意位置拖動,但如果我離開的看法砸任何地方,他們沒有更多的可見文本視圖
我用OnTouchListener()和OnDragListener ()on textviews
幫我解決這個問題
我的活動
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;
}
}
}
我在佈局上ACTION_DROP事件相應的座標
<?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>