Android: Switching screens by dragging over the touch screen

Posted May 29th @ 12:17 am by Boyan Tsolov

Advertisement

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.

3. For the above to work, you need to add a global variable called downXValue that will store the X value when the finger was pressed down. Add the line below at the top of the class:

...
public class Activity1 extends Activity implements OnTouchListener{

    private float downXValue;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
...

4. Now, you we will edit the main.xml layout. This is different from the main.xml from the previous post in two ways:

  • The two buttons that switched the views have been removed, because we don’t need them anymore and
  • I added an ID to the main LinearLayout so that I may reference it in my code.

Here is the entire main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff"
    android:id="@+id/layout_main"
    >

    <ViewFlipper android:id="@+id/details"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">  

        <LinearLayout
               android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="#ffffff">

            <TextView android:id="@+id/tv_country"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textColor="#000000"
            android:textStyle="bold"
            android:textSize="18px"
            android:text="Country" >
            </TextView>
            <Spinner android:text=""
            android:id="@+id/spinner_country"
            android:layout_width="200px"
            android:layout_height="55px">
            </Spinner>
        </LinearLayout> 

        <LinearLayout
               android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="#ffffff">

            <TextView android:id="@+id/tv_income"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textColor="#000000"
            android:textStyle="bold"
            android:textSize="18px"
            android:text="Income" >
            </TextView>
            <EditText android:text=""
            android:id="@+id/et_income"
            android:layout_width="200px"
            android:layout_height="55px">
            </EditText>
        </LinearLayout> 

    </ViewFlipper>

</LinearLayout>

5. We will have to add a listener for the OnTouch() event in the OnCreate() method of the Activity1 class will be. Add the following two lines:

...
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set main.XML as the layout for this Activity
        setContentView(R.layout.main);

        // Add these two lines
        LinearLayout layMain = (LinearLayout) findViewById(R.id.layout_main);
        layMain.setOnTouchListener((OnTouchListener) this);
...

6. You should also remove the two Button OnClick() events and listeners, because those buttons do not exist anymore. Here is the final version of the Activity1.java class:

package com.warriorpoint.taxman3;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.ViewFlipper;

public class Activity1 extends Activity implements OnTouchListener{

    float downXValue;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set main.XML as the layout for this Activity
        setContentView(R.layout.main);

        // Add these two lines
        LinearLayout layMain = (LinearLayout) findViewById(R.id.layout_main);
        layMain.setOnTouchListener((OnTouchListener) this); 

        // Add a few countries to the spinner
        Spinner spinnerCountries = (Spinner) findViewById(R.id.spinner_country);
        ArrayAdapter countryArrayAdapter = new ArrayAdapter(this,
                    android.R.layout.simple_spinner_dropdown_item,
                    new String[] { "Canada", "USA" });
        spinnerCountries.setAdapter(countryArrayAdapter);

    }

    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;
    }

}

That’s it! Run it!

You will see that the button is gone and dragging across to the left or right will switch the screens!

01 animation

Disclaimer: The back animation is not perfect, I still have to figure out why. It flickers a little. If you figure it out to animate properly please drop me a comment. Thanks!



2 Trackbacks/Pingbacks

  1. Pingback: V?n ?? modify color focus item trong ListView on January 18, 2011
  2. Pingback: Android incoming call slider video on January 1, 2013

24 Comments

  1. Mathias
    September 30, 2009 at 11:50

    Hi,
    Nice post. Very helpful.
    I think I’ve the answer to your animation issue. (maybe you’ve already find it)

    Instead of using only the 2 animations proposed you have to create 2 more like this :

    a push_right_out.xml

    and a push_right_in.xml

    You have to replace what happens when you click on a button :

    Instead of setAnimation(…..);
    use
    setInAnimation(view.getContext(), R.anim.push_left_in);
    setOutAnimation(view.getContext(), R.anim.push_left_out);

    for the 1 to 2 view
    and

    vf.setInAnimation(view.getContext(), R.anim.push_right_in);
    vf.setOutAnimation(view.getContext(), R.anim.push_right_out);
    for the 2 to 1 view

    And you’ll have a very smoothy animation in the two ways.

  2. Martin
    March 17, 2010 at 14:24

    Hi, It is nice starting. But i’m facing problems handling imagebutton controls under multi touch events using the same code. How do we resolve it? When i have three image buttons and kept it as button.setOnTouchListener(this); for three buttons, onTouch() can be able to detect only one button at a time, cann’t be able to detect all the button click when i click on all the buttons at a time as multi touch purpose. How do we resolve it in this case?

  3. Joseph Cheek
    April 16, 2010 at 13:33

    Awesome tutorial, thanks! I will definitely be using this in my apps.

  4. Jed
    May 20, 2010 at 07:52

    This tutorial is AWESOME!!! I have been struggling building a app and all I had to do is add my elements in the main xml and it works. I also compared the size of my own application that I’m building vs this one, this one is ~145 KB & mine is 2.3 MB.

    THANK YOU VERY MUCH!

  5. Jed
    May 20, 2010 at 07:54

    Boyan ROCKS! Please keep adding such good tutorials.

  6. Cruz
    July 2, 2010 at 19:47

    Take a look at the alpha settings in each animation xml file. That’s the cause of the flicker.
    It animates from 1.0 to 0.0, then quickly sets it back to 1.0

  7. brits
    August 25, 2010 at 06:07

    Thanks Mathias!
    That’s exactly solution for this problem :)

  8. Mark
    October 24, 2010 at 13:03

    To get the animations smooth and so they move correctly across screens. Use what mathias said and look at the comments for the previous tutorial which uses buttons to set the correct values of the right animations…the values are basically just inverted.

  9. Parth
    January 22, 2011 at 05:51

    Hey…I am trying to implement your program,but I keep getting this error : “onTouchListener cannot be resolved to a type’ and ‘ The method setOnTouchListener(View.OnTouchListener) in the type View is not applicable for the arguments (onTouchListener)’

    1)I have imported android.view.View.OnTouchListener;
    Eclipse did not create the stub method…
    and am getting an error where I call setOnTouchListener((onTouchListener) this);

    Am i missing something???Please help…its urgent…

    Thanks in advance…Parth.

  10. Patrick
    March 28, 2011 at 22:54

    Thanks….
    This actually helped me so much and is the essential part for my first app :)

  11. JohnyXD
    April 19, 2011 at 07:55

    Hello, thank you for this tutorial it helped me a lot.
    Although I have a little problem: I want to detect ACTION_DOWN even if I started from a botton. That’s because my activity has many elements so the space allowed for dragging is small.
    Thank you.

  12. Chris
    April 25, 2011 at 19:28

    Based on the very first poster (Mathias) I had trouble figuring out how the 4 xml files should be set exactly. For those who still haven’t figured it out, here come the parameters which I used for a perfectly smooth slide in both directions:

    push_left_in.xml:

    android:fromXDelta=”100%p”
    android:toXDelta=”0″
    android:fromAlpha=”0.0″
    android:toAlpha=”1.0″

    push_left_out.xml:

    android:fromXDelta=”0″
    android:toXDelta=”-100%p”
    android:fromAlpha=”1.0″
    android:toAlpha=”0.0″

    push_right_in:

    android:fromXDelta=”-100%p”
    android:toXDelta=”0″
    android:fromAlpha=”0.0″
    android:toAlpha=”1.0″

    push_right_out:

    android:fromXDelta=”0″
    android:toXDelta=”100%p”
    android:fromAlpha=”1.0″
    android:toAlpha=”0.0″

    PS.: Thanks to all you guys and especially the blog creator. It helped me alot. Thats how I give my thanks back to you.

  13. Robson
    June 13, 2011 at 11:37

    Thx Chris, you saved me some time figuring it out :)

  14. Najhi
    July 19, 2011 at 06:27

    Use
    for right animation
    vf.setAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_right));

    and

    for left animation
    vf.setAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_left));

  15. Peter
    August 1, 2011 at 09:26

    it’s possible create this without xml layout’s ? just hate xml layouts and always i craeted view’s programmaticaly.

  16. Munk3y
    August 13, 2011 at 09:27

    Thanks!!!! It help me a lot!! =D

  17. Pintoo
    December 9, 2011 at 17:45

    Hi,

    I want a similar kind of animation, but in a circular fashion.
    Basically, i want to switch between activities and that switching should give an effect of an arc shaped movement just like a pendulum moves..
    It would be really helpful if you can share knowledge on achieving the same.

    Thanks,
    Pintoo

  18. Oleg
    February 8, 2012 at 22:40

    Thank you for the time you saved me :)

  19. emrullah
    February 22, 2012 at 03:34

    Why nobody talked about R.anim? What is the “anim”? Eclipse doesn’t allow me to add an anim class to the R.java manually, and it doesn’t add it automatically. What can I do?

  20. emrullah
    February 22, 2012 at 04:33

    I found the answer of my previous question but I have another question :) Does the above code provide swithing the screens just in one activity? I have many activities and want to switch screens passing another activity. How can I do it?
    Regards.

  21. Lars Thomas
    March 5, 2012 at 12:09

    This explanation is the best Google found. Thanks for your work!

  22. Deepak
    September 11, 2012 at 01:31

    Thanks for such a good tutorial.

    Can u perform action on MotionEvent.Action_Move.

  23. Jr
    October 2, 2012 at 12:37

    I trying to figure how to slide de screens exact like google play, and launcher does, without have to add AndroidSupport http://android-developers.blogspot.com.br/2011/08/horizontal-view-swiping-with-viewpager.html
    The tutorial is diferent,since it captures the movement and change, and not actualy drag the view.. =\ any?

  24. Leandro Bortolotto
    December 2, 2013 at 22:12

    Hi,

    I wanna put a ScrollView in the first Layout to scroll it, but this doesn’t work. Any suggestions about this error?

    tks

Leave a comment

Standard Login

Options:

Colors

  • does d cause impotence
  • bid
  • cold sore dose
  • krymas kaina
  • dosage for a dog
  • and
  • difference between
  • msds tablets
  • ds
  • contro i pidocchi
  • hct tab 32-12.5
  • lek
  • timberland white
  • buy uk
  • low dose hormonal acne
  • dosage kids
  • ds missed dose
  • malarone pregnancy
  • therapeutic serum level range
  • tmj pain
  • kegunaan
  • 30 mg 14 tablet
  • starter pack dosage
  • can you take and together
  • patient information sheet
  • first day taking
  • not working
  • tablets
  • side effects increased appetite
  • fruit juice commercial
  • normal dose of for bladder infection
  • achilles heel
  • bill kaulitz overdose
  • band russia
  • teratogenic effects
  • can i take and advil
  • will raise my blood pressure
  • skin side effects
  • and at same time
  • generation kennett square
  • chlamydia pneumoniae
  • 5 follicules
  • for withdrawal from opiates
  • can you take vitamin b while
  • used high fsh levels
  • vs zoloft for anxiety
  • dosage
  • and lupus
  • ampollas novartis
  • quickly does work
  • cream ebay
  • alcohol detox
  • banda cristiana
  • dosages available
  • calcium channel blockers
  • drug interaction
  • once a day
  • a inne leki
  • zoloft vs social anxiety
  • and bipolar
  • not effective 2009
  • taking provera with
  • when doesn't work
  • for severe depression
  • o que A
  • dog
  • product information australia
  • used for opiate withdrawal
  • reviews side effects
  • can u smoke weed while on
  • relief uk
  • contre indication
  • vitamin c
  • fast oral jelly
  • ad anti-dandruff shampoo 7 oz
  • menopause symptoms
  • odt kit orange
  • taking
  • source
  • and uterine lining thin
  • generic
  • vs
  • gonal f iui
  • keramag nr. 1 flachspA?l-wc wandhAngend
  • twitter
  • mechanism of action
  • launch date
  • can you take tums
  • relprevv pharmacokinetics
  • relief mr spc
  • accidentally took 1200 mg of
  • patient assistance form
  • can you take same time
  • cheap
  • ec 500
  • chances of twins on 100mg
  • what is the maximum daily dose of
  • mania
  • pregnancy calculator using
  • para sirve d
  • como age o no aborto
  • canadian pharmacy no prescription
  • can i mix and allegra
  • pomata costo
  • missed pill
  • drug manufacturer
  • taking after ectopic
  • liquid taste
  • 2 months in
  • side effects liver
  • for pcos side effects
  • treatment for osteoarthritis
  • success stories
  • for uti prophylaxis
  • hct urination
  • can take nattokinase
  • correction albumin calculator
  • deaths children
  • birth control acne
  • e trittico
  • discontinuation symptoms
  • informacion en espanol
  • max dose consta
  • bula composiAA?o
  • rash sun
  • technology ga
  • about medication
  • used for chlamydia
  • chemical structure
  • 4 weeks on
  • vs stroke prevention
  • buy no prescription
  • 1 por dia
  • frova
  • use 2 jelly intercourse
  • side effects stroke
  • 3mg
  • to treat uti in men
  • direct branford ct
  • inr levels
  • side effects stopping suddenly
  • cold medicine while
  • 5 mg
  • can i take extra to lose weight
  • will show up on a drug test
  • taking together
  • rapaflo and the same
  • generic release date november
  • 40 mg
  • walmart pharmacy generic
  • combined with iui success rates
  • ambien interaction
  • withdrawal---headaches
  • eltroxin
  • thyroid disease
  • in early pregnancy
  • 0.25mg
  • active ingredient
  • contraindications
  • as a histamine blocker
  • switching
  • can you drink beer while on
  • starter pack dosage
  • menstrual cramps
  • m aventis
  • samples for physicians
  • coupon
  • when is going generic in usa
  • herpes transmission study
  • can you take together
  • severe constipation
  • are and the same
  • difference between and
  • westcort
  • simplex 1 herpes
  • and provera for infertility
  • chlamydia pneumoniae
  • brain zaps withdrawal
  • and interaction
  • otc twice a day
  • a xyzal
  • buy from india
  • buy vancouver bc
  • side effects pregnant women
  • too much dry mouth
  • will show up drug test
  • la 4mg capsules
  • memory loss
  • does cause night sweats
  • vs
  • hcg pct
  • liquid dosage for children
  • rebate
  • aumenta a prolactina
  • alternatives
  • my yahoo account sending spam
  • peanut allergy
  • prn
  • para que sirve el tabletas
  • herpes genitale e
  • high blood pressure tablets
  • tinea versicolor treatment
  • through iv
  • can you take while your pregnant
  • 20 mg price cvs
  • vs
  • adhd treatment
  • why doesn't work for some men
  • package insert
  • herpes genitalis
  • irregular heartbeat
  • 6 mp and
  • trip report
  • autism side effects
  • for a 6 year old
  • sublingual canada
  • planters warts
  • starter kit orange
  • what is drug
  • tablets sale
  • mixing and poppers
  • does have a generic brand
  • 70 mg
  • doesn't work
  • pronunciation
  • dosage for ibs
  • no side effects
  • clonazepam and combination
  • dosage 0.5mg
  • cheaper than
  • e gh
  • difference between ds septra ds
  • daily vs 36 hour
  • ds side effects in children
  • will cause diarrhea
  • results 3 months
  • versus
  • interaction between benadryl
  • symptoms of pregnancy on
  • can you take with
  • cheapest
  • syrup
  • and for pct
  • questions
  • buy online
  • antibiotic cost
  • indications and usage
  • chloride vs. la
  • children's suspension
  • libido cure
  • signs and symptoms of high level
  • most effective way use
  • krople ulotka dawkowanie
  • price for 10mg
  • uses and side effects
  • vitamin e capsules
  • ac 120 mg
  • alternative cat bite
  • side effects sun exposure
  • equivalent dose
  • made my headache worse
  • for pneumonia in children
  • can take oxycodone
  • is it safe to take benadryl with
  • information birth control pill
  • unterschied
  • que es el medicamento
  • taking later than day 5
  • conversion
  • and together
  • leg edema
  • snorting
  • tac dung thuoc
  • for acne does it work
  • and weight gain
  • cure
  • e sport
  • sore throat after
  • neuroleptic malignant
  • syrup
  • para que mas sirve el
  • dosage mims
  • blurred vision
  • vs anyone
  • prix 20 mg
  • reverse hair loss
  • janssen pharmaceutical
  • 12.5 mg tablets
  • generic ingredients
  • buy uk
  • zombie
  • que es 0.5 mg
  • online canada
  • do people take to get high
  • hair loss
  • herbal 8000 mg
  • slow release
  • taking for allergies
  • 200mg capsules
  • side effects 10 20 mg
  • does snorting make you high
  • hot water cylinder
  • j code for
  • express tabletki
  • is a psychotropic drug
  • diarrhea
  • for meningitis exposure
  • comparison
  • is or or best
  • bad dreams
  • pharmacological classification
  • dopo quanto tempo funziona
  • fracture hip
  • antibiotics for sinus infection
  • withdrawal nausea
  • back pain
  • for e coli diarrhea
  • when will patent expire
  • better than
  • exercise after
  • nausea after
  • cream webmd
  • how long to cure chlamydia
  • xanax
  • in pregnancy first trimester
  • perianal fistula
  • a nurofen
  • como se toma la pastilla para abortar
  • cheap canada free shipping
  • turmeric
  • used to treat fibromyalgia
  • can you buy chemist australia
  • versus
  • and bipolar
  • dosierung kinder
  • 10 mg enough
  • will feel better
  • and together
  • withdrawal symptoms how long
  • patient education
  • cost uk
  • m cmi
  • lethal dose
  • missed dose monthly
  • adverse side effects
  • 6315540691
  • for children
  • and alcohol interaction
  • ventures company llc
  • joint pain knees
  • pediatric dosing
  • white stool
  • and
  • versus
  • versus zoloft
  • ditropan vs
  • serophene over counter
  • pediatric dosing
  • 16 mg astrazeneca
  • medication for bipolar
  • high blood pressure medication
  • y cerveza
  • quantidade de berotec e para nebulizaAA?o
  • and azor
  • nuclear pa
  • usar 5 meses
  • transsexual
  • and alcohol interaction
  • manufacturer
  • aspirin half life
  • dementia
  • long term effects taking
  • medicine side effects
  • can take 1600 mg
  • vs
  • reviews side effects
  • 4 refundowany
  • gel drug class
  • suspension stability
  • sweating side effect
  • 9.5 mg
  • side effects weight
  • via g-tube
  • 300 g
  • success stories
  • what is 200mg capsules used for
  • effects smoking
  • conflitto tra e turchia
  • topical
  • and
  • jaundice
  • i dojenje
  • bijsluiter gsk
  • withdrawal symptoms
  • shampoo side effects men
  • hep c
  • e ipertensione
  • weight loss side effects
  • after a stroke
  • does cure stomach ulcers