Here you will find an explaination on how to handle touch events:
http://developer.android.com/guide/topics/ui/ui-events.html
Then, in the on touch method, you need to
- detect when the user put his finger down
- store the finger's position
- detect when the user moves
- compare with previous position
- detect when the user stops touching the screen
Example (using code from http://developer.android.com/training/graphics/opengl/touch.html)
@Override
public boolean onTouchEvent(MotionEvent e) {
// MotionEvent reports input details from the touch screen
// and other input controls. In this case, you are only
// interested in events where the touch position changed.
float x = e.getX();
float y = e.getY();
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN:
mIsDown = true;
break;
case MotionEvent.ACTION_MOVE:
float dx = x - mPreviousX;
float dy = y - mPreviousY;
// Here you can try to detect the swipe. It will be necessary to
// store more than the previous value to check that the user move constantly in the same direction
detectSwipe(dx, dy);
case MotionEvent.ACTION_UP:
mIsDown = false;
break;
}
mPreviousX = x;
mPreviousY = y;
return true;
}
With this simple case, you wouldn't even need to stor when the user puts his finger down or up (since moving implies a finger down) but it can be useful to have the boolean value stored)
Good luck with your app
EDIT:
It seems you edited your post with some code. You say that you don't get the explected results but you don't say what you get. This might be useful for us to help you.
You should try to find if a library that detects swipe movements already exists. I'm pretty sure there is many out there
EDIT 2:
I assume you button is a simple android.Button. One solution could be to create a class that extends Button (ex: MySwipableButton). in your xml, you create a layout that contains your MySwipableButton, and give it enought place to be moved (for example, it has width=fill_parent, since you want it to swipe on the while screen). MySwipableButton implements onTouch to store the position in which the button should be (using the method you already have)
MySwipableButton would also overwrite onDraw(Graphics g)
. In onDraw, you would paint the button (super.draw()) at the place it must be (regarding the current swipe) and leave the rest of the view empty
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…