Created
May 30, 2015 23:43
-
-
Save slightfoot/a7de4ecdc6cf06c68640 to your computer and use it in GitHub Desktop.
Move View Touch Listener Example
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
import android.view.GestureDetector; | |
import android.view.MotionEvent; | |
import android.view.View; | |
/** | |
* @author Simon Lightfoot <[email protected]> | |
*/ | |
public class MoveViewTouchListener | |
implements View.OnTouchListener | |
{ | |
private GestureDetector mGestureDetector; | |
private View mView; | |
public MoveViewTouchListener(View view) | |
{ | |
mGestureDetector = new GestureDetector(view.getContext(), mGestureListener); | |
mView = view; | |
} | |
@Override | |
public boolean onTouch(View v, MotionEvent event) | |
{ | |
return mGestureDetector.onTouchEvent(event); | |
} | |
private GestureDetector.OnGestureListener mGestureListener = new GestureDetector.SimpleOnGestureListener() | |
{ | |
private float mMotionDownX, mMotionDownY; | |
@Override | |
public boolean onDown(MotionEvent e) | |
{ | |
mMotionDownX = e.getRawX() - mView.getTranslationX(); | |
mMotionDownY = e.getRawY() - mView.getTranslationY(); | |
return true; | |
} | |
@Override | |
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) | |
{ | |
mView.setTranslationX(e2.getRawX() - mMotionDownX); | |
mView.setTranslationY(e2.getRawY() - mMotionDownY); | |
return true; | |
} | |
}; | |
} |
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
import android.os.Bundle; | |
import android.support.v7.app.AppCompatActivity; | |
import android.view.View; | |
public class TestActivity | |
extends AppCompatActivity | |
{ | |
@Override | |
protected void onCreate(Bundle savedInstanceState) | |
{ | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_test); | |
final View testItem = findViewById(R.id.test_item); | |
testItem.setOnTouchListener(new MoveViewTouchListener(testItem)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment