How to create Swipe Navigation in an Android App

When talking about Android Apps, the first thing that comes to mind is variety. There are so many varieties of Android apps providing the user with beautiful dynamic UI. One such feature is to navigate in our Android Apps using left and right swipes as opposed to clicking on buttons. Not only does it look more simple and elegant but also provides ease of access to the user. There are many apps which use this swipe feature to swipe through different activities in the app. For example, the popular chatting app, Snapchat, uses it to swipe through lenses, chats and stories. Here, we will learn how to implement swipe views in our own Android app.

We can implement this by use of two features:

  1. Fragments A fragment is just a part of an activity. We can have a fragment that takes up part of a screen or a whole screen. Or we can show multiple fragments at the same time to make up a whole screen. Within an activity, we can also swap out different fragments with each other. 
  2. ViewPager ViewPager is a class in Java which is used in conjunction with Fragments. It is mostly used for designing the UI of the app.

How does it work?
First we need to set an adapter on the ViewPager using the setAdapter() method. The adapter which we set is called FragmentPagerAdapter which is an abstract class in Java. Hence, we create our own SampleFragmentPagerAdapter which extends from FragmentPagerAdapter and displays our Fragments on the screen. When we launch the app in our device, the ViewPager asks the SampleFragmentPagerAdapter how many pages are there to swipe through. The getCount() method of the adapter returns this answer to the ViewPager. Then the ViewPager asks for the Fragment which is at the 0th position and the adapter returns that particular fragment which is then displayed by ViewPager on our screen. When we swipe left, ViewPager asks adapter for the Fragment at 1st position and similarly, it is displayed on the screen and it continues so on.

Step by step implementation:
We will be creating three fragments that is three screens that the user can swipe through. Then we will add these fragments to our FragmentPagerAdapter and finally set it on ViewPager. 
Note: To run these codes, you need to copy and paste them in Android Studio as it won’t run on the IDE!

  • Step1: Creating Fragments: 
    To create a fragment, click on app > Java > com.example.android(Right Click) > New > Fragment > Fragment(Blank) 
     



    We can create as many Fragments as we want but since we will be displaying only three screens, hence we will create three Fragments. 
    Now we will open our Fragments and copy this code over there:
     

    Java

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    package com.example.android.gfg;
      
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
      
    public class Fragment1 extends Fragment {
      
        @Override
        public View onCreateView(
            LayoutInflater inflater,
            ViewGroup container,
            Bundle savedInstanceState)
        {
            return inflater
                .inflate(
                    R.layout.fragment_1,
                    container, false);
        }
    }

    chevron_right

    
    

    Explanation: 
     

    • We are importing v4 Fragment with BuildTools version 23.0.2 . If we get an error in our imports, we must make sure that our BuildTools and SDK version corresponds to the libraries which we import.
    • We name our Fragment as Fragment1.
    • Fragment1 displays the layout fragment_1.xml which we will make now.
  • Step 2: Creating layouts for Fragments: 
    Each Fragment needs to display a layout. We can design this layout anyhow we want. Here is the code to how we would implement this layout as:
     

    XML

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="16dp">
      
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/gfg"/>
      
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. "
            android:textSize="20sp"
            android:textColor="#81c784"/>
    </LinearLayout>

    chevron_right

    
    

    This looks like: 
     

    Similarly, we will create two more Fragments and a respective layout for each one of them.

  • Step 3: Creating our FragmentPageAdapter: 
    Now that we have all our three Fragments and three layouts are associated with each one of them, we will now build our FragmentPageAdapter and call it SimpleFragmentPageAdapter. This can be done by first creating a new Java Class and naming it as SimpleFragmentPageAdapter. Here’s the code it will contain:
     

    Java

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    package com.example.android.gfg;
      
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentPagerAdapter;
      
    public class SimpleFragmentPagerAdapter
        extends FragmentPagerAdapter {
      
        public SimpleFragmentPagerAdapter(
            FragmentManager fm)
        {
            super(fm);
        }
      
        @Override
        public Fragment getItem(int position)
        {
            if (position == 0) {
                return new Fragment1();
            }
            else if (position == 1) {
                return new Fragment2();
            }
            else {
                return new Fragmnet3();
            }
        }
      
        @Override
        public int getCount()
        {
            return 3;
        }
    }

    chevron_right

    
    

    Explanation: 
     

    • The getItem() method returns the Fragment at specified position. So first will be Fragment1 and upon swiping left, we will get the other Fragments in the same order.
    • The getCount() method returns the number of Fragments there are to be displayed, which, in this case is three.
  • Step 3: Creating MainActivity.Java and activity_main.xml : 
    Now that we have everything ready, the last step is just to make our MainActivity.Java and activity_main.xml files. They can vary largely depending on the app we are making but in this case, the files are pretty simple and looks like this: 

    activity_main.xml

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?xml version="1.0" encoding="utf-8"?>
      
    <LinearLayout
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context="com.example.android.viewpager.MainActivity">
      
        <android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
      
    </LinearLayout>

    chevron_right

    
    

    MainActivity.Java

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    package com.example.android.gfg;
      
    import android.os.Bundle;
    import android.support.v4.view.ViewPager;
    import android.support.v7.app.AppCompatActivity;
      
    public class MainActivity
        extends AppCompatActivity {
      
        @Override
        protected void onCreate(
            Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
      
            // Set the content of the activity
            // to use the activity_main.xml
            // layout file
            setContentView(R.layout.activity_main);
      
            // Find the view pager that will
            // allow the user to swipe
            // between fragments
            ViewPager viewPager
                = (ViewPager)findViewById(
                    R.id.viewpager);
      
            // Create an adapter that
            // knows which fragment should
            // be shown on each page
            SimpleFragmentPagerAdapter
                adapter
                = new SimpleFragmentPagerAdapter(
                    getSupportFragmentManager());
      
            // Set the adapter onto
            // the view pager
            viewPager.setAdapter(adapter);
        }
    }

    chevron_right

    
    

    Output:

    Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




    My Personal Notes arrow_drop_up

    Check out this Author's contributed articles.

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.