1
我正在創建一個android應用程序,將在主佈局上放置圖像。我的問題是如何拖動圖像並將其放在另一個佈局上。從一個佈局拖動圖像到另一個佈局 - android
我的一些代碼來自:http://www.vogella.com/articles/AndroidDragAndDrop/article.html
我的代碼工作,只要你拖動它在同一版面它不另佈局移動。
這是我的代碼:
public class MainActivity extends Activity {
int _xDelta;
int _yDelta;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.myimage1).setOnTouchListener(new MyTouchListener());
findViewById(R.id.myimage2).setOnTouchListener(new MyTouchListener());
findViewById(R.id.myimage3).setOnTouchListener(new MyTouchListener());
findViewById(R.id.myimage4).setOnTouchListener(new MyTouchListener());
findViewById(R.id.topleft).setOnDragListener(new MyDragListener());
findViewById(R.id.topright).setOnDragListener(new MyDragListener());
findViewById(R.id.bottomleft).setOnDragListener(new MyDragListener());
findViewById(R.id.bottomright).setOnDragListener(new MyDragListener());
}
private final class MyTouchListener implements OnTouchListener {
public boolean onTouch(View view, MotionEvent motionEvent) {
final int X = (int) motionEvent.getRawX();
final int Y = (int) motionEvent.getRawY();
switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
LinearLayout.LayoutParams lParams = (LinearLayout.LayoutParams) view.getLayoutParams();
_xDelta = X - lParams.leftMargin;
_yDelta = Y - lParams.topMargin;
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_POINTER_DOWN:
break;
case MotionEvent.ACTION_POINTER_UP:
break;
case MotionEvent.ACTION_MOVE:
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view.getLayoutParams();
layoutParams.leftMargin = X - _xDelta;
layoutParams.topMargin = Y - _yDelta;
layoutParams.rightMargin = -250;
layoutParams.bottomMargin = -250;
view.setLayoutParams(layoutParams);
break;
}
return true;
}
}
class MyDragListener implements OnDragListener {
@Override
public boolean onDrag(View v, DragEvent event) {
int action = event.getAction();
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
break;
case DragEvent.ACTION_DRAG_ENTERED:
break;
case DragEvent.ACTION_DRAG_EXITED:
break;
case DragEvent.ACTION_DROP:
View view = (View) event.getLocalState();
ViewGroup owner = (ViewGroup) view.getParent();
owner.removeView(view);
LinearLayout container = (LinearLayout) v;
container.addView(view);
view.setVisibility(View.VISIBLE);
break;
case DragEvent.ACTION_DRAG_ENDED:
default:
break;
}
return true;
}
}}
希望你能幫助我。
AbsoluteLayout已棄用。使用觸摸事件(移動動作)獲取x和y並放置在那些x和y上。 –
我沒有任何想法可以幫助我嗎?謝謝! – MMakati
幫助自己http://stackoverflow.com/questions/9398057/android-move-a-view-on-touch-move-action-move –