Android ViewSwitcher with GestureDetector Tutorial - Truiton
Skip to content

Android ViewSwitcher with GestureDetector Tutorial

Let there be light

Often while working on Android app development, a situation is encountered where one has to switch one view with another view. For this purpose we can use Android’s ViewSwitcher class. One of the many examples I can quote here, is a simple Login Screen. In a simple login screen the idle scenario would be that a user enters a username, password and hits Login button. After Login button is tapped, the screen should disappear with an animation and a loading icon or message should show up, while the app is communicating with a background web service. As you might have understood here two layouts are required and hence this functionality can be easily made with Android ViewSwitcher by switching views.

But for this tutorial lets consider a little more complex scenario. Android ViewSwitcher class can also be used with Android GestureDetector class. In this Android ViewSwitcher with GestureDetector Tutorial I am going to switch between two views with Android ViewSwitcher class. This switch would be done by a swipe gesture which would be detected by Android GestureDetector class’s GestureDetector.OnGestureListener interface.

This Android ViewSwitcher with GestureDetector Tutorial is a part of my series of three on Android ViewSwitcher and View Flipper. Both of these classes are used to transform a view into another view with some animation by ViewAnimator class. But in my series of tutorials I have used Android’s XMLs, reason for it will be explained later in this tutorial. Firther if you wish to read my complete series have a look at the links below:

  1. Android ViewSwitcher with GestureDetector Tutorial
  2. Android ViewFlipper Tutorial
  3. Android ViewSwitcher vs ViewFlipper

Android ViewSwitcher

There are often situations in Android where we have to switch between views on run time. To make the transition smooth we can use Android ViewSwitcher class. This is used to perform a switch between two views in android. To make the transition smooth and attractive we can use ViewAnimator class, or we can use Android’s animation XML files like android.R.anim.fade_out. Also if you wish to define your own animation XML you are free to do so. Now lets have a look at activity_truiton_view_switcher.xml layout file where the Android ViewSwitcher view is defined:

<ViewSwitcher xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/ViewSwitcher1"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Layout #1"
            android:textStyle="bold"
            android:layout_gravity="center" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/truiton"
            android:layout_marginTop="50dp"
            android:layout_gravity="center" />

    </LinearLayout>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/truiton_full"
            android:layout_alignParentTop="true"/>
        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Layout #2"
            android:textStyle="bold"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true" />
    </RelativeLayout>
</ViewSwitcher>

In the above layout file for Android ViewSwitcher have a look that the main enclosing tag, that is <ViewSwitcher> tag, this tag contains exactly two layouts. Please note that ViewSwitcher can contain only two layouts, as per its official documentation. For the record I tried adding another layout, and the app crashed !! Have a look at the exception below:

07-14 08:30:00.691: E/AndroidRuntime(1048): FATAL EXCEPTION: main
07-14 08:30:00.691: E/AndroidRuntime(1048): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.truiton.viewswitcherexample/com.truiton.viewswitcherexample.TruitonViewSwitcherActivity}: java.lang.IllegalStateException: Can't add more than 2 views to a ViewSwitcher

Android ViewSwitcher class also has the ability to use viewFactory interface. This interface is used to add views by setFactory method. Further ViewSwitcher.ViewFactory interface uses makeView method, which actually creates a view inside ViewSwitcher. Now comes the part where we swipe out our view on the basis of user input, and in this tutorial I would be doing this by the help of Android GestureDetector class.

Android GestureDetector

In Android we can detect user’s touch input by Android GestureDetector class. This class can detect various gestures by the supplied MotionEvents. We can implement Android GestureDetector class in 3 ways:

  1. GestureDetector.OnDoubleTapListener – This is an interface which is used to identify double tap or confirmed single tap event.
  2. GestureDetector.OnGestureListener – This is the standard interface which is used to detect Android Gestures.
  3. GestureDetector.SimpleOnGestureListener – This is a class which can be extended incase you want to use only specific methods, as when we implement an interface all of its unimplemented methods are added in our main class.

In this Android ViewSwitcher with GestureDetector Tutorial I will be using GestureDetector.OnGestureListener interface since it has all the standard methods which are generally used. Although I would be using only one of its method for my purpose and that is onFling. Lets have a look at the TruitonViewSwitcherActivity.java :

package com.truiton.viewswitcherexample;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MotionEvent;
import android.widget.ViewSwitcher;

public class TruitonViewSwitcherActivity extends Activity implements
 OnGestureListener {
 ViewSwitcher switcher;
 GestureDetector myDetector;
 String Log_Tag = "Truiton-ViewSwitcher";

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_truiton_view_switcher);
 switcher = (ViewSwitcher) findViewById(R.id.ViewSwitcher1);
 switcher.setInAnimation(this, android.R.anim.fade_in);
 switcher.setOutAnimation(this, android.R.anim.fade_out);
 myDetector = new GestureDetector(this, this);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
 // Inflate the menu; this adds items to the action bar if it is present.
 getMenuInflater().inflate(R.menu.truiton_view_switcher, menu);
 return true;
 }

 @Override
 public boolean onTouchEvent(MotionEvent event) {
 myDetector.onTouchEvent(event);
 return super.onTouchEvent(event);
 }

 @Override
 public boolean onDown(MotionEvent arg0) {
 Log.v(Log_Tag, "On Down");
 return false;
 }

 @Override
 public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
 float velocityY) {
 if (e1.getRawY() > e2.getRawY()) {
 switcher.showNext();
 Log.v(Log_Tag, "Show Next");
 } else {
 switcher.showPrevious();
 Log.v(Log_Tag, "Show Previous");
 }
 return false;
 }

 @Override
 public void onLongPress(MotionEvent e) {
 Log.v(Log_Tag, "Long Press");

 }

 @Override
 public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
 float distanceY) {
 Log.v(Log_Tag, "On Scroll");
 return false;
 }

 @Override
 public void onShowPress(MotionEvent e) {
 Log.v(Log_Tag, "Show Press");
 }

 @Override
 public boolean onSingleTapUp(MotionEvent e) {
 Log.v(Log_Tag, "Single Tap Up");
 return false;
 }

}

The code in above class is easy to understand, here an object of ViewSwitcher class is initialized and an appropriate animation is assigned to it by setInAnimation and setOutAnimation methods of Android ViewSwitcher class. Also you might observe that this class implements OnGestureListener interface. This Android GestureDetector.OnGestureListener helps us to implement the methods through which we can detect gestures.

The first method used here is onTouchEvent, this method triggers the callbacks to Android GestureDetector and further to appropriate interface i.e. OnGestureListener. Without onTouchEvent no callbacks would occur and hence no touch inputs or Android gestures would be detected.

Now that we have our Android GestureDetector and OnGestureListener, we need to use its methods to detect the inputs and determine the swipe. Here I used the onFling method which detects the start and end point of a touch event. Have a look at the final output screens :

In this tutorial, I displayed how to use Android ViewSwitcher with GestureDetector class and make swiping screens. This is just one of the example which I could think of these classes. These classes could be used in many more ways. If you like this tutorial share it with your friends at Facebook, Google+ and also like our Facebook page to stay connected.

Leave a Reply

Your email address will not be published. Required fields are marked *