In this post I will show you how to use the touch screen so that you can drag your finger across the screen, and it will switch the screen for you – “iPhone style”!
For this I will be implemented OnTouchListener and overrided the method OnTouch().
To start off, we need to create an Activity with two screens. The two screens will be implemented using a ViewFlipper in the main.xml layout file. Follow the steps in this blog post to set yourself up: Android: Switching screens in an Activity with animations (using ViewFlipper).
1. Now that you have yourself set up, open the Activity1 class.
2. Make the class implement OnTouchListener. The top of the class will look like this:
...
import android.view.View.OnTouchListener;
public class Activity1 extends Activity implements OnTouchListener{
...
2. You will have to override the OnTouch() method as well. If you were using eclipse, it might have created the method stub for you:
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
return false;
}
Here is the method that you need to use instead:
public boolean onTouch(View arg0, MotionEvent arg1) {
// Get the action that was done on this touch event
switch (arg1.getAction())
{
case MotionEvent.ACTION_DOWN:
{
// store the X value when the user's finger was pressed down
downXValue = arg1.getX();
break;
}
case MotionEvent.ACTION_UP:
{
// Get the X value when the user released his/her finger
float currentX = arg1.getX();
// going backwards: pushing stuff to the right
if (downXValue < currentX)
{
// Get a reference to the ViewFlipper
ViewFlipper vf = (ViewFlipper) findViewById(R.id.details);
// Set the animation
vf.setAnimation(AnimationUtils.loadAnimation(this, R.anim.push_left_out));
// Flip!
vf.showPrevious();
}
// going forwards: pushing stuff to the left
if (downXValue > currentX)
{
// Get a reference to the ViewFlipper
ViewFlipper vf = (ViewFlipper) findViewById(R.id.details);
// Set the animation
vf.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.push_left_in));
// Flip!
vf.showNext();
}
break;
}
}
// if you return false, these actions will not be recorded
return true;
}
What I’ve done is added a CASE statement. On press down of the finger we save the current X value. On press up of the finger, after the dragging motion has finished, I check the X value again. I compare the two X values and I make a logical decision whether I should switch the screens forwards or backwards.
Read the rest of this entry »