how to drag an image by touching in android? Please Help me with a sample code.
Asked
Active
Viewed 4.2k times
3 Answers
28
package com.examples.Touchmoveimage;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
public class Touchmoveimage extends Activity {
int windowwidth;
int windowheight;
private LayoutParams layoutParams;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
windowwidth = getWindowManager().getDefaultDisplay().getWidth();
windowheight = getWindowManager().getDefaultDisplay().getHeight();
final ImageView balls = (ImageView) findViewById(R.id.ball);
balls.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
LayoutParams layoutParams = (LayoutParams) balls.getLayoutParams();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
int x_cord = (int) event.getRawX();
int y_cord = (int) event.getRawY();
if (x_cord > windowwidth) {
x_cord = windowwidth;
}
if (y_cord > windowheight) {
y_cord = windowheight;
}
layoutParams.leftMargin = x_cord - 25;
layoutParams.topMargin = y_cord - 75;
balls.setLayoutParams(layoutParams);
break;
default:
break;
}
return true;
}
});
}
}
works good!!

A. Badakhshan
- 1,045
- 7
- 22

Prateek Raj
- 3,966
- 6
- 39
- 50
5
You need to read about Gestures especially Scroll - which is drag in Android - and Fling.
I recommend to you this tutorial. Its exactly what you are looking for.

M.ES
- 920
- 14
- 30
-
Great as this also introduces some Android Animation stuff like Interpolator. Source available here: https://code.google.com/p/android-gestures-tutorials/source/checkout – Pascal Jan 22 '16 at 12:27
0
There is no direct way to do drag and drop in Android. You have to write some classes. Look into DragController.java, DragLayer.java in Launcher project.

Vinay
- 4,743
- 7
- 33
- 43