Created
August 2, 2019 17:38
-
-
Save mohamad-shafaee/5f86a85bea40777afbb416b27693cf25 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MainActivity extends AppCompatActivity { | |
int mActivePointerId = MotionEvent.INVALID_POINTER_ID; | |
float mLastTouchX; | |
float mLastTouchY; | |
float mPosX = 0f; | |
float mPosY = 0f; | |
CViewN cview; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
cview = (CViewN) findViewById(R.id.cview_1); | |
} | |
@Override | |
public boolean onTouchEvent(MotionEvent ev){ | |
final int action = ev.getActionMasked(); | |
switch (action){ | |
case MotionEvent.ACTION_DOWN: | |
{ | |
final int pointerIndex = ev.getActionIndex(); | |
final float x = ev.getX(pointerIndex); | |
final float y = ev.getY(pointerIndex); | |
// Remember where we started (for dragging) | |
mLastTouchX = x; | |
mLastTouchY = y; | |
mActivePointerId = ev.getPointerId(pointerIndex); | |
break; | |
} | |
case MotionEvent.ACTION_MOVE: | |
{ | |
// Find the index of the active pointer and fetch its position | |
final int pointerIndex = ev.findPointerIndex(mActivePointerId); | |
final float x = ev.getX(pointerIndex); | |
final float y = ev.getY(pointerIndex); | |
// Calculate the distance moved | |
final float dx = x - mLastTouchX; | |
final float dy = y - mLastTouchY; | |
mPosX += dx; | |
mPosY += dy; | |
// Remember this touch position for the next move event | |
mLastTouchX = x; | |
mLastTouchY = y; | |
cview.setX((int) mPosX); | |
cview.setY((int) mPosY); | |
//invalidate(); | |
break; | |
} | |
case MotionEvent.ACTION_UP: | |
{ | |
mActivePointerId = MotionEvent.INVALID_POINTER_ID; | |
break; | |
} | |
case MotionEvent.ACTION_CANCEL: | |
{ | |
mActivePointerId = MotionEvent.INVALID_POINTER_ID; | |
break; | |
} | |
case MotionEvent.ACTION_POINTER_UP: | |
{ | |
final int pointerIndex = ev.getActionIndex(); | |
final int pointerId = ev.getPointerId(pointerIndex); | |
if(pointerId == mActivePointerId){ | |
// This was our active pointer going up. Choose a new | |
// active pointer and adjust accordingly. | |
final int newPointerIndex = pointerIndex == 0 ? 1 : 0; | |
mLastTouchX = ev.getX(newPointerIndex); | |
mLastTouchY = ev.getY(newPointerIndex); | |
mActivePointerId = ev.getPointerId(newPointerIndex); | |
} | |
break; | |
} | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment