Touch and Drag Image in Android

how to drag an imageview in an android application using touch

this post look similar.have a look.
how to drag an image by touching in android?
Keep Coding! :)

android drag and drop ImageView onTouchListener

If you need to support gingerbread you can take a look at my example here

https://github.com/NAYOSO/android-dragview

if you only need to support jelly bean above you can use the Drag and Drop from android library you can see it from this article

http://developer.android.com/guide/topics/ui/drag-drop.html

For some explanation about the Drag and Drop view
at first you need t create the touch listener and then call startDrag to start draging. As simple as that.

private final class dragTouchListener implements OnTouchListener {

@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(v);
v.startDrag(data, shadowBuilder, v, 0);
return true;
} else {
return false;
}
}

}

To monitor the target of dropping place you can use onDragListener

private class dropListener implements OnDragListener {

View draggedView;
CustomTextView dropped;

@Override
public boolean onDrag(View v, DragEvent event) {
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
draggedView = (View) event.getLocalState();
dropped = (CustomTextView) draggedView;
draggedView.setVisibility(View.INVISIBLE);
break;
case DragEvent.ACTION_DRAG_ENTERED:
break;
case DragEvent.ACTION_DRAG_EXITED:
break;
case DragEvent.ACTION_DROP:

CustomTextView dropTarget = (CustomTextView) v;
dropTarget.setText(dropped.getText().toString());
break;
case DragEvent.ACTION_DRAG_ENDED:
break;
default:
break;
}
return true;
}

}

As you can see from my code there is many event but the main one is when the view is start being dragged, dropped and ended.

Don't forget to set the listener to view

    tvDrag.setOnTouchListener(new dragTouchListener());
tvDrop.setOnDragListener(new dropListener())

I hope my explanation is clear enough!
If you have further question I will try to answer it tonight or tomorrow :)

Drag a view on touch and back to origin position on touch release

 top2AxOriginXCoordinate = top2AX.getX();
top2AxOriginYCoordinate = top2AX.getY();

may be this two variables are 0.0 , if it's so then told me I'll help you

Touch and drag image in android

public class TouchBall extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

int w=getWindowManager().getDefaultDisplay().getWidth()-25;
int h=getWindowManager().getDefaultDisplay().getHeight()-25;

BallView ballView=new BallView(this,w,h);
setContentView(ballView);
}

}
public class BallView extends SurfaceView implements SurfaceHolder.Callback {

private Bitmap bitmap ;
private MyThread thread;
private int x=20,y=20;int width,height;

public BallView(Context context,int w,int h) {
super(context);

width=w;
height=h;
thread=new MyThread(getHolder(),this);
getHolder().addCallback(this);
setFocusable(true);
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);

bitmap =BitmapFactory.decodeResource(getResources(), R.drawable.ball_green);
canvas.drawColor(Color.BLUE);//To make background
canvas.drawBitmap(bitmap,x-(bitmap.getWidth()/2),y-(bitmap.getHeight()/2),null);

}

@Override
public boolean onTouchEvent(MotionEvent event) {

x=(int)event.getX();
y=(int)event.getY();

if(x<25)
x=25;
if(x> width)
x=width;
if(y <25)
y=25;
if(y > 405)
y=405;
return true;
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,int height) {
// TODO Auto-generated method stub

}

@Override
public void surfaceCreated(SurfaceHolder holder) {

thread.startrun(true);
thread.start();

}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {

thread.startrun(false);
thread.stop();

}
}

thread:

public class MyThread extends Thread {

private SurfaceHolder msurfaceHolder;
private BallView mballView;
private boolean mrun =false;

public MyThread(SurfaceHolder holder, BallView ballView) {

msurfaceHolder = holder;
mballView=ballView;
}

public void startrun(boolean run) {

mrun=run;
}

@Override
public void run() {

super.run();
Canvas canvas;
while (mrun) {
canvas=null;
try {
canvas = msurfaceHolder.lockCanvas(null);
synchronized (msurfaceHolder) {
mballView.onDraw(canvas);
}
} finally {
if (canvas != null) {
msurfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}

}

Android - move an ImageView on screen (Like dragging)

Your routine works for the most part. In the following code, I have commented out sections that are not needed and made notations for those parts that need some explanation. Here is what the finished product looks like:

Sample Image

This graphic explains how the left margin is calculated. The same type of calculation applies to the top margin.

Sample Image

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnTouchListener {

int windowwidth; // Actually the width of the RelativeLayout.
int windowheight; // Actually the height of the RelativeLayout.
private ImageView mImageView;
private ViewGroup mRrootLayout;
private int _xDelta;
private int _yDelta;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// We are interested when the image view leaves its parent RelativeLayout
// container and not the screen, so the following code is not needed.
// DisplayMetrics displaymetrics = new DisplayMetrics();
// this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
// windowwidth = displaymetrics.widthPixels;
// windowheight = displaymetrics.heightPixels;
mRrootLayout = (ViewGroup) findViewById(R.id.root);
mImageView = (ImageView) mRrootLayout.findViewById(R.id.im_move_zoom_rotate);

// These these following 2 lines that address layoutparams set the width
// and height of the ImageView to 150 pixels and, as a side effect, clear any
// params that will interfere with movement of the ImageView.
// We will rely on the XML to define the size and avoid anything that will
// interfere, so we will comment these lines out. (You can test out how a layout parameter
// can interfere by setting android:layout_centerInParent="true" in the ImageView.
// RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(150, 150);
// RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(150, 150);
// mImageView.setLayoutParams(layoutParams);
mImageView.setOnTouchListener(this);

// Capture the width of the RelativeLayout once it is laid out.
mRrootLayout.post(new Runnable() {
@Override
public void run() {
windowwidth = mRrootLayout.getWidth();
windowheight = mRrootLayout.getHeight();
}
});
}

// Tracks when we have reported that the image view is out of bounds so we
// don't over report.
private boolean isOutReported = false;

public boolean onTouch(View view, MotionEvent event) {
final int X = (int) event.getRawX();
final int Y = (int) event.getRawY();

// Check if the image view is out of the parent view and report it if it is.
// Only report once the image goes out and don't stack toasts.
if (isOut(view)) {
if (!isOutReported) {
isOutReported = true;
Toast.makeText(this, "OUT", Toast.LENGTH_SHORT).show();
}
} else {
isOutReported = false;
}
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
// _xDelta and _yDelta record how far inside the view we have touched. These
// values are used to compute new margins when the view is moved.
_xDelta = X - view.getLeft();
_yDelta = Y - view.getTop();
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_DOWN:
case MotionEvent.ACTION_POINTER_UP:
// Do nothing
break;
case MotionEvent.ACTION_MOVE:
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) view
.getLayoutParams();
// Image is centered to start, but we need to unhitch it to move it around.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
lp.removeRule(RelativeLayout.CENTER_HORIZONTAL);
lp.removeRule(RelativeLayout.CENTER_VERTICAL);
} else {
lp.addRule(RelativeLayout.CENTER_HORIZONTAL, 0);
lp.addRule(RelativeLayout.CENTER_VERTICAL, 0);
}
lp.leftMargin = X - _xDelta;
lp.topMargin = Y - _yDelta;
// Negative margins here ensure that we can move off the screen to the right
// and on the bottom. Comment these lines out and you will see that
// the image will be hemmed in on the right and bottom and will actually shrink.
lp.rightMargin = view.getWidth() - lp.leftMargin - windowwidth;
lp.bottomMargin = view.getHeight() - lp.topMargin - windowheight;
view.setLayoutParams(lp);
break;
}
// invalidate is redundant if layout params are set or not needed if they are not set.
// mRrootLayout.invalidate();
return true;
}

private boolean isOut(View view) {
// Check to see if the view is out of bounds by calculating how many pixels
// of the view must be out of bounds to and checking that at least that many
// pixels are out.
float percentageOut = 0.50f;
int viewPctWidth = (int) (view.getWidth() * percentageOut);
int viewPctHeight = (int) (view.getHeight() * percentageOut);

return ((-view.getLeft() >= viewPctWidth) ||
(view.getRight() - windowwidth) > viewPctWidth ||
(-view.getTop() >= viewPctHeight) ||
(view.getBottom() - windowheight) > viewPctHeight);
}
}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<ImageView
android:id="@+id/im_move_zoom_rotate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="@drawable/circle" />

</RelativeLayout>


Related Topics



Leave a reply



Submit