4
我想在另一個ImageView或Layout中完成一個簡單的ImageView拖放操作。下面是我想要做的Android將ImageView拖放到另一個ImageView或佈局中
我知道做到這一點的唯一方法照片通過具有2點線性佈局,一個「FROM」和「TO」,並分配到第二佈局的背景灰色的信件的圖像。
這裏是我的代碼
public class MainActivity extends Activity implements OnTouchListener,
OnDragListener {
private static final String LOGCAT = null;
/*
* Here are the links I've been using
* http://www.techrepublic.com/blog/software-engineer/try-androids-useful-drag-and-drop-api/
* http://codingjunkie.net/android-drag-and-drop-part-2/
* http://javapapers.com/android/android-drag-and-drop/
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.letter_a).setOnTouchListener(this); // My yellow letter a image
findViewById(R.id.top_container).setOnDragListener(this); // My 1st linear layout
findViewById(R.id.bottom_container).setOnDragListener(this); // My 2nd linear layout with "grayed a" image
}
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
view.startDrag(null, shadowBuilder, view, 0);
view.setVisibility(View.INVISIBLE);
return true;
} else {
return false;
}
}
@Override
public boolean onDrag(View layoutview, DragEvent dragevent) {
int action = dragevent.getAction();
View view = (View) dragevent.getLocalState();
switch (action) {
case DragEvent.ACTION_DRAG_STARTED:
break;
case DragEvent.ACTION_DRAG_ENTERED:
break;
case DragEvent.ACTION_DRAG_EXITED:
break;
case DragEvent.ACTION_DROP:
ViewGroup owner = (ViewGroup) view.getParent();
owner.removeView(view);
LinearLayout container = (LinearLayout) layoutview;
container.addView(view);
view.setVisibility(View.VISIBLE);
break;
case DragEvent.ACTION_DRAG_ENDED:
Log.d(LOGCAT, "Drag ended");
if (dropEventNotHandled(dragevent)){
view.setVisibility(View.VISIBLE);
}
break;
default:
break;
}
return true;
}
private boolean dropEventNotHandled(DragEvent dragEvent) {
return !dragEvent.getResult();
}
}
我已經設法獲得onTouch和ondrag當工作和移動時檢測,但我想將其鎖定到位,因此它不能拖回到它原來的地方。
非常感謝!
太棒了!非常感謝。 –