Trying to understand onTouch method - android

I have an image and it moves to my finger position when I touch it, Everything is working but I want to know what these variables do.
Part of code
//I'm trying since the morning to understand what these variables do but I failed so can someone tell me why we put these variables?
dX = view.getX() - event.getRawX();
dY = view.getY() - event.getRawY();
Full code
#SuppressLint("ClickableViewAccessibility")
#Override
public boolean onTouch(View view, MotionEvent event) {
if (view.getId() == R.id.img_view) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
dX = view.getX() - event.getRawX();
dY = view.getY() - event.getRawY();
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
view.setX(event.getRawX() + dX);
view.setY(event.getRawY() + dY);
}
}
return true;
}

dX and dY is a difference between top left corner of this view and touch point on this view - you are touching view somewhere in the middle of it, almost never on its edge (pixel on 0,0 coordinates). when ACTION_MOVE occurs then you are using setX/setY methods for changing position, which are setting position of this top left corner - for preserving feeling of dragging (no view jump, smooth drag) you have to add these initial difference. use Log.i(..) and observe Logcat tab in Android Studio, you will notice which value is responsible for which param of touch/view

Related

How can I move an object around the screen by dragging in Android?

So in my layout I have this ball which I want to drag around the screen. I tried using the onTouch() method, and these are my results:
1)((Button)findViewById(R.id.ball)).setY(event.getY());
((Button)findViewById(R.id.ball)).setX(event.getX());
This one is very glitchy for some reason. I try to move the ball and it just quickly goes back and forth between two different places.
2) ((Button)findViewById(R.id.ball)).setY(event.getRawY());
((Button)findViewById(R.id.ball)).setX(event.getRawX());
This one works a bit smoother, but when I start the movement the ball just teleports to some other place. It works fine except for that part where it "teleports"
What I want to achieve:
A normal drag movement of the ball where the ball is right beneath the finger (x and y coordinates of the ball match the x and y coordinates of the touch)
I can add screen recordings explaining the two cases above if needed
First make your activity implement View.OnTouchListener and import the requested method:
public class MyActivity extends AppCompatActivity implements View.OnTouchListener {}
Then change newly created onTouch method like below:
float dX, dY;
#Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
dX = view.getX() - event.getRawX();
dY = view.getY() - event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
view.animate()
.x(event.getRawX() + dX)
.y(event.getRawY() + dY)
.setDuration(0)
.start();
break;
default:
return false;
}
return true;
}
and finally set this onTouch method to your view:
ball.setOnTouchListener(this);

Moving a View with ACTION_MOVE in Scaled Layout

Hello! Thank you for reading.
Based upon this answer, I integrated View dragging like so:
float dX, dY;
#Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
dX = view.getX() - event.getRawX();
dY = view.getY() - event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
setX(event.getRawX() + dX);
setY(event.getRawY() + dY);
break;
default:
return false;
} return true;
}
However, the View's position relative to my finger is proportionally offset with the scale of the parent layout. In other words, when I start zooming in the layout, View dragging breaks.
I've been debugging for quite a bit and it seems that even knowing the parent layout scale (as, say, dScale), I can't use that value in a way that fixes the offset completely.
I cannot even reach a point where the distance between my finger and the View is constant.
To note that the issue is only observable when the parent's scale is not equal to 1.
.
Thank you very much for your help!
For further reference, this situation can be solved by applying the parent's scale to the getRawX() methods in both occurrences. I somehow hadn't tried that...
float dX, dY;
#Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
dX = view.getX() - event.getRawX() / dScale;
dY = view.getY() - event.getRawY() / dScale;
break;
case MotionEvent.ACTION_MOVE:
setX(event.getRawX() / dScale + dX);
setY(event.getRawY() / dScale + dY);
break;
default:
return false;
} return true;
}
I'd also recommend putting the MOVE case first in the switch.
I suppose the reasoning behind this solution can be vaguely explained by "view positioning methods know how to handle scaling, touch callback methods don't".
Hope this will help some!

Android move view to a touched position

I'm trying to develop an android application similar to "on color measurement" or "color grab" which are already on google play.
I have problem with getting the exact position of a view (which acts like focus square) and move it to the position where the user touches the screen. I have done a lot of searches but all of them ended in onTouchEvent() which I used it but it does not work properly or maybe I have done something wrong.
Actually the view moves but it won't be placed exactly where the user touch, it will go below the touched area in y axis with a distance.
here is my code where the mFocusRectangle is the custom view which I want to move to the touched position:
#Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
if (event.getPointerCount() > 1) {
// handle multi-touch events
} else {
// handle single touch events
if(action==MotionEvent.ACTION_DOWN){
}
if (action == MotionEvent.ACTION_UP) {
int pointerId = event.getPointerId(0);
int pointerIndex = event.findPointerIndex(pointerId);
// Get the pointer's current position
float x = event.getX(pointerIndex);
float y = event.getY(pointerIndex);
mFocusRectangle.showStart();
mFocusRectangle.setX(x);
mFocusRectangle.setY(y);
}
}
return true;
}
I have also tried MotionEvent.ACTION_DOWN but the result is the same.
Thanks in advance.
try this
float x = event.getX(pointerIndex) - (mFocusRectangle.getWidth() / 2);
float y = event.getY(pointerIndex) - (mFocusRectangle.getHeight() / 2);
credits:
Manitoba - Android move view on touch event

How do you make an onTouchListener keep going as long as the view is being pressed?

I am using a small square RelativeLayout as a game pad for movement in a neighboring GLSurfaceView.
I set it up so that in the onTouch method of the RelativeLayout's onTouchListenner I call a method built into the GLSurfaceView that updates the translation and rotation coordinates for my drawing.
I have everything working fine, except for the fact that touch events are only triggered if the user moves his or her finger on the RelativeLayout.
I would like it to feel a little bit like a joystick: if you leave your finger pressed on the top of the RelativeLayout, then you will keep going "up" ( or more programatically: the event.getX() and event.getY() that were sent last should get looped, or re-sent, in the GLSurfaceView until the user either moves his finger inside the RelativeLayout, or stops touching the RelativeLayout altogether.)
What should I use to detect whether or not the RelativeLayout is currently being touched (even if there is no motion in the said touch)?
Thanks!
So this is what I came up pretty much simultaneously with csmcklvey
if(event.getAction()==MotionEvent.ACTION_UP)
gM.isTouchedL = false;
else
gM.isTouchedL = true;
return true;
Where .isTouchedL is the "control boolean" I use in the GLSurfaceView
Green lit csmc's answer anyways! :)
I have used rotation animation in one of my apps, which is using the onTouchEven of view. Major function has been performed in event "ACTION_MOVE". It will help you, to get through.
public boolean onTouch(View v, MotionEvent event)
{
final float xc = volumeButton.getWidth() / 2;
final float yc = volumeButton.getHeight() / 2;
final float x = event.getX();
final float y = event.getY();
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
{
// volumeButton.clearAnimation();
// mCurrAngle = Math.toDegrees(Math.atan2(x - xc, yc - y));
break;
}
case MotionEvent.ACTION_MOVE:
{
mPrevAngle = mCurrAngle;
mCurrAngle = Math.toDegrees(Math.atan2(x - xc, yc - y));
animate(mPrevAngle, mCurrAngle, 100);
break;
}
case MotionEvent.ACTION_UP :
{
mPrevAngle = mCurrAngle = 0;
break;
}
}
return true;
}
You might be able to use the event.getAction() method of the MotionEvent parameter of your onTouch() method. You can check to see if it is MotionEvent.ACTION_DOWN or MotionEvent.ACTION_UP.
if (event.getAction() == MotionEvent.ACTION_DOWN) {
//start something
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
//stop something
}
My thought is that you might be able to start or stop a thread in this manner but either way this might at least give you some more information about when the user actually presses and lifts his/her finger.

Android: Allow TextView to be Dragged Outside of RelativeLayout

I've created an OnTouchListener that will allow me to drag views around the screen. This works well, except for one problem:
My views resize instead of leaving the parent. They are in a RelativeLayout, which I suspect is contributing to the problem. They only resize when touching the right or bottom boundaries of my RelativeLayout.
I'm hoping there is a simple solution to this problem, (ideally not involving resizing the RelativeLayout), but I haven't found a solution yet.
Ideally, this solution would be applicable for all views, as I use this OnTouchListener for TextViews as well as ImageViews. I was hoping to find an XML solution. I'm assuming others have dealt with this issue??
PS: Before I post this..I've just remembered I believe there is a flag for hitting a RelativeLayout's border, so maybe I can apply negative margin to the TextView when that happens. Thoughts?
EDIT
Here is my OnTouchListener:
// Dragging functionality for all views and double tap to remove
// functionality for ImageViews
final OnTouchListener onTouchListener = new OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
v.bringToFront();
//if(v instanceof android.widget.ImageView)
//mScaleDetector.onTouchEvent(event);
layoutParams = (LayoutParams) v.getLayoutParams();
switch (event.getActionMasked())
{
case MotionEvent.ACTION_DOWN:
// Where the user started the drag
pressed_x = (int) event.getRawX();
pressed_y = (int) event.getRawY();
if (v instanceof android.widget.ImageView)
{
curTime = System.currentTimeMillis();
if(curTime - prevTime <= DOUBLE_TAP_INTERVAL)
{
v.setVisibility(View.GONE);
}
prevTime = curTime;
}
case MotionEvent.ACTION_MOVE:
// Where the user's finger is during the drag
final int x = (int) event.getRawX();
final int y = (int) event.getRawY();
// Calculate change in x and change in y
dx = x - pressed_x;
dy = y - pressed_y;
// Update the margins
layoutParams.leftMargin += dx;
layoutParams.topMargin += dy;
v.setLayoutParams(layoutParams);
// Save where the user's finger was for the next ACTION_MOVE
pressed_x = x;
pressed_y = y;
break;
default:
break;
}
return true;
}
}

Categories

Resources