How to determine the end of a touch-events set? - android

I have a small app, which uses a fullscreen activity and where I can drag an ImageView.
Now my solution works like this: I change the position of the ImageView according to the drag of the finger, so basically I'm adding the delta x (previousX - currentX) to the position of the ImageView. Now the problem is determining the previousX. It works fine for the first time, since I'm testing whether it's 0, if it's null it means the app is just started and the previous x can become the new x, however the dragging movement becomes ugly as soon as you move the finger away after dragging and start dragging again by putting the finger in a different spot than you finished dragging the first time (because it's virtually impossible to put it in the same place. So the previousX is the one from the last drag, so when you start the second drag it jumps the x difference from the previous x to the new one. I either need to change a different way of calculating this, or determine when the finger gets away from screen and the series of drag events are finished.
This is what my code for the touch event looks like:
#Override
public boolean onTouch(View v, MotionEvent event) {
LayoutParams layoutParams = (LayoutParams) img
.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;
}
if (previousX == 0) {
previousX = x_cord;
}
if (previousY == 0) {
previousY = y_cord;
}
layoutParams.leftMargin = layoutParams.leftMargin
+ (x_cord - previousX);
layoutParams.topMargin = layoutParams.topMargin
+ (y_cord - previousY);
img.setLayoutParams(layoutParams);
previousX = x_cord;
previousY = y_cord;
break;
default:
break;
}
return true;
}
});

Related

How to create a movable button which doesn't move out of the screen

I'm using this code to move a button in the screen but when I reach the sides it is moving out of the screens.
private float mPrezX, mPrevY;
private static final int MAX_CLICK_DURATION = 200;
private long startClickTime;
#Override
public boolean onTouch(View view, MotionEvent event) {
int action = event.getActionMasked();
Button gvup = (Button)findViewById(R.id.giveup);
gvup.setBackground(getResources().getDrawable(R.drawable.btn));
switch (action ) {
case MotionEvent.ACTION_DOWN: {
mPrevX = view.getX() - event.getRawX();
mPrevY = view.getY() - event.getRawY();
startClickTime = Calendar.getInstance().getTimeInMillis();//!!
gvup.setBackground(getResources().getDrawable(R.drawable.btn1));
break;
}
case MotionEvent.ACTION_MOVE:
{
view.animate()
.x(event.getRawX() + mPrevX)
.y(event.getRawY() + mPrevY)
.setDuration(0)
.start();
gvup.setBackground(getResources().getDrawable(R.drawable.btn1));
break;
}
case MotionEvent.ACTION_CANCEL:
gvup.setBackground(getResources().getDrawable(R.drawable.btn1));
break;
case MotionEvent.ACTION_UP:
long clickDuration = Calendar.getInstance().getTimeInMillis() - startClickTime;
if(clickDuration < MAX_CLICK_DURATION) {
//click event has occurred
gvup.setBackground(getResources().getDrawable(R.drawable.btn));
giveUp();
}
break;
}
return true;
}
I'm also changing its background color if pressed and also made it clickable.
I need to keep that button inside the layout.
I have also tried this and this links but both of these approaches leading to squeeze the button when moved to the sides.
Please help.
Thanks in advance.
Well you need to get its X location and add its width to it to see where the "right" edge is and compare if it greater or equal to your viewport's width. I haven't written JAVA in a while but that should do the trick.
Are you checking its location?
Perhaps
int rightEdge = currentPos.X + itsWidth;
if(rightEdge >= screenWidth) // something here
Maybe in your animate() method do your checking. Its hard for me to guess withough looking at what is making this happen. What is firing the event? What is event.getRawX() equal to? Is that a touch point on the screen? Are you animating after the point is selected? Or you can define a min/max x and min/max y and not let your circle past that.
view.animate()
if( .x(event.getRawX() + mPrevX) > screenWidth ){
.x(screenwidth - circleWidth)
} // do the same for the Y - must check the max and min for both Y and X
.x(event.getRawX() + mPrevX)
.y(event.getRawY() + mPrevY)
.setDuration(0)
.start();

Move, rotate and scale text using custom layout in android

Hi I want to do something like this
When user presses rotate icon, text contained in box should gradually rotate and using scale icon, text should be resized.
Right now I am using this code for moving the textview everywhere on the screen
private int _xDelta;
private int _yDelta;
#Override
public boolean onTouch(View view, MotionEvent event) {
final int X = (int) event.getRawX();
final int Y = (int) event.getRawY();
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
RelativeLayout.LayoutParams lParams = (RelativeLayout.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:
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
layoutParams.leftMargin = X - _xDelta;
layoutParams.topMargin = Y - _yDelta;
layoutParams.rightMargin = -250;
layoutParams.bottomMargin = -250;
view.setLayoutParams(layoutParams);
break;
}
elementslayout.invalidate();
return true;
}
It is working fine.
On long press of textview I want to show the layout with rotate and scale icon.
My question is,
How to create this type of layout for textview and do rotate and scale accordingly?
I have seen many codes for rotate and scale using matrix like
http://judepereira.com/blog/multi-touch-in-android-translate-scale-and-rotate/
But don't know how to use it here.
I also want to do the same thing, Rotate,Scale as well as move textview all together. I found a link for text rotation here.
Android Two finger rotation
This works totally fine for the text rotation. You just need to add
txt.setRotation(-angle);
In the onRotation Method. May be that helps you.

View animation while moving on Screen in android?

I had 2 views in an activity. One full screen (View1) and other small (View2), half the size of View1.
I can move View2, over View1 by catching onTouch listeners (ACTION_UP/ACTION_DOWN). But i want to show animation/dragging image of View2 while moving on View1. Any suggestion on how to implement this, will be appreciated.
Currently, for moving the View2 in four corner, i'm setting the Layout params in ACTION_UP.
Code::
public boolean onTouch(View view, MotionEvent motionEvent) {
RelativeLayout.LayoutParams layoutParams =(RelativeLayout.LayoutParams)view.getLayoutParams();
int dx=0,dy=0;
switch (motionEvent.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
int x = (int) motionEvent.getX();
int y = (int) motionEvent.getY();
dx = (int) motionEvent.getRawX() - layoutParams.leftMargin;
dy = (int)motionEvent.getRawY() - layoutParams.topMargin;
break;
case MotionEvent.ACTION_MOVE:
layoutParams.leftMargin = (int) ((int) motionEvent.getRawX()-dx);
layoutParams.topMargin = (int) ((int)motionEvent.getRawY()- dy);
view.setLayoutParams(layoutParams);
break;
case MotionEvent.ACTION_UP:
view.setLayoutParams(layoutParams);
break;
}
return true;
}
Use ACTION_MOVE and calculate the offset by checking a pointer's x or y value. After that set weight or height/width parameter of the floating View.

Jumping ImageView while dragging. getX() and getY() values are jumping

I've created an onTouchListener for dragging Views. Images drag smoothly if I use getRawX() and getRawY(). The problem with that is the image will jump to the second pointer when you place a second pointer down then lift the first pointer.
This onTouchListener attempts to fix that issue by keeping track of the pointerId. The problem with this onTouchListener is while dragging an ImageView, the ImageView jumps around pretty crazily. The getX() and getY() values jump around.
I feel like I'm doing this correctly. I don't want to have to write a custom view for this because I've already implemented a scaleGestureDetector and written a custom rotateGestureDetector that work. Everything works fine but I need to fix the issue I get when using getRawX() and getRawY().
Does anybody know what I'm doing wrong here?
Here's my onTouchListener:
final View.OnTouchListener onTouchListener = new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
relativeLayoutParams = (RelativeLayout.LayoutParams) v.getLayoutParams();
final int action = event.getAction();
switch (action & MotionEvent.ACTION_MASK)
{
case MotionEvent.ACTION_DOWN:
{
final float x = event.getX();
final float y = event.getY();
// Where the user started the drag
lastX = x;
lastY = y;
activePointerId = event.getPointerId(0);
break;
}
case MotionEvent.ACTION_MOVE:
{
// Where the user's finger is during the drag
final int pointerIndex = event.findPointerIndex(activePointerId);
final float x = event.getX(pointerIndex);
final float y = event.getY(pointerIndex);
// Calculate change in x and change in y
final float dx = x - lastX;
final float dy = y - lastY;
// Update the margins to move the view
relativeLayoutParams.leftMargin += dx;
relativeLayoutParams.topMargin += dy;
v.setLayoutParams(relativeLayoutParams);
// Save where the user's finger was for the next ACTION_MOVE
lastX = x;
lastY = y;
v.invalidate();
break;
}
case MotionEvent.ACTION_UP:
{
activePointerId = INVALID_POINTER_ID;
break;
}
case MotionEvent.ACTION_CANCEL:
{
activePointerId = INVALID_POINTER_ID;
break;
}
case MotionEvent.ACTION_POINTER_UP:
{
// Extract the index of the pointer that left the touch sensor
final int pointerIndex = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = event.getPointerId(pointerIndex);
if(pointerId == activePointerId)
{
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
lastX = (int) event.getX(newPointerIndex);
lastY = (int) event.getY(newPointerIndex);
activePointerId = event.getPointerId(newPointerIndex);
}
break;
}
}
return true;
}
};
image1.setOnTouchListener(onTouchListener);
The issue was simple, but unexpected. getRawX/Y() returns absolute coordinates, while getX/Y() returns coordinates relative to the view. I would move the view, reset lastX/Y, and the image wouldn't be in the same spot anymore so when I get new values they'd be off. In this case I only needed where I originally pressed the image (not the case when using `getRawX/Y').
So, the solution was to simply remove the following:
// Save where the user's finger was for the next ACTION_MOVE
lastX = x;
lastY = y;
I hope this will help somebody in the future, because I've seen others with this problem, and they had similar code to me (resetting lastX/Y)
After a lot of research, I found this to be the issue, getRawX is absolute and getX is relative to view. hence use this to transform one to another
//RawX = getX + View.getX
event.getRawX == event.getX(event.findPointerIndex(ptrID1))+view.getX()
I have One tip & think it will help.
invalidate() : does only redrawing a view,doesn't change view size/position.
What you should use is
requestLayout(): does the measuring and layout process. & i think requestLayout() will be called when call setLayoutParams();
So Try by removing v.invalidate()
or try using view.layout(left,top,right,bottom) method instead of setting layoutParams.

Transfer longpress from one android view to another, without releasing finger

We have a longpress detection on a button. When detected, the view should be dismissed (back to the game view) and the object chosen with the button shall be at the coordinates of the longpress. That's the easy part, the hard part is to then change the coordinates with the finger, without releasing it.
Okay so i'm trying to reformulate this: We have two views displayed on top of eachother. What we want is a longclick detected in the top view, to then dismiss the top view, and without releasing the finger, get touchevents in the bottom view.
This is our class gameView: (this code contains a lot of code unneccesay for the problem)
#Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mode = DRAG;
//We assign the current X and Y coordinate of the finger to startX and startY minus the previously translated
//amount for each coordinates This works even when we are translating the first time because the initial
//values for these two variables is zero.
startX = event.getX() - previousTranslateX;
startY = event.getY() - previousTranslateY;
break;
case MotionEvent.ACTION_MOVE:
translateX = event.getX() - startX;
translateY = event.getY() - startY;
gestureHandler.setTranslation(translateX, translateY);
//We cannot use startX and startY directly because we have adjusted their values using the previous translation values.
//This is why we need to add those values to startX and startY so that we can get the actual coordinates of the finger.
double distance = Math.sqrt(Math.pow(event.getX() - (startX + previousTranslateX), 2) +
Math.pow(event.getY() - (startY + previousTranslateY), 2)
);
if(distance > 0) {
dragged = true;
}
break;
case MotionEvent.ACTION_POINTER_DOWN:
mode = ZOOM;
scaleToX = event.getX();
scaleToY = event.getY();
break;
case MotionEvent.ACTION_UP:
mode = NONE;
dragged = false;
//All fingers went up, so let's save the value of translateX and translateY into previousTranslateX and
//previousTranslate
previousTranslateX = translateX;
previousTranslateY = translateY;
int x = (int)((-translateX/scaleFactorX)+(event.getX()/this.scaleFactorX));
int y = (int)((-translateY/scaleFactorY)+(event.getY()/this.scaleFactorY));
map.click(getContext(), x, y);
for(CastleTile castleTile : map.getCastleTiles()) {
if(castleTile.getRect().contains((int)((-translateX/scaleFactorX)+(event.getX()/this.scaleFactorX)), (int)((-translateY/scaleFactorY)+(event.getY()/this.scaleFactorY)))){
Log.d("Castle to your service", "Boes");
castleSettings.show();
}
}
break;
case MotionEvent.ACTION_POINTER_UP:
mode = DRAG;
//This is not strictly necessary; we save the value of translateX and translateY into previousTranslateX
//and previousTranslateY when the second finger goes up
previousTranslateX = translateX;
previousTranslateY = translateY;
break;
}
detector.onTouchEvent(event);
//We redraw the canvas only in the following cases:
//
// o The mode is ZOOM
// OR
// o The mode is DRAG and the scale factor is not equal to 1 (meaning we have zoomed) and dragged is
// set to true (meaning the finger has actually moved)
if ((mode == DRAG && scaleFactorX != 1f && scaleFactorY != 1f && dragged) || mode == ZOOM) {
invalidate();
}
return true;
}
#Override
public boolean onLongClick(View v) {
castleSettings.dismiss();
return true;
}
And this is the gestureHandler:
public void onLongPress(MotionEvent event) {
map.longClick(context, (int)((-translateX/scaleFactorX)+(event.getX()/this.scaleFactorX)), (int)((-translateY/scaleFactorY)+(event.getY()/this.scaleFactorY)));
}
Sorry for eventual lack of information or bad explaination :)

Categories

Resources