我想在另一个ImageView或Layout中完成一个简单的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工作并检测移动时间,但我想把它锁定到位,这样它就不会被拖回原来的位置。
非常感谢!
答案 0 :(得分:2)
如果它应该留在bottom_container中,只需取消注册监听器,如果它已被丢弃,例如像这样:
case DragEvent.ACTION_DROP:
ViewGroup owner = (ViewGroup) view.getParent();
owner.removeView(view);
LinearLayout container = (LinearLayout) layoutview;
container.addView(view);
view.setVisibility(View.VISIBLE);
if(container.getId()==R.id.bottom_container){
view.setOnTouchListener(null);
owner.setOnDragListener(null);
}
break;