Open In App

How to Create Swipe Navigation in Android?

Last Updated : 30 Aug, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 a beautiful dynamic UI. One such feature is to navigate our Android Apps using left and right swipes as opposed to clicking on buttons. Not only does it look more simple and more elegant but also provides ease of access to the user. There are many apps that 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 that 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 the adapter for the Fragment at 1st position and similarly, it is displayed on the screen and it continues so on.

Note: To run these codes, you need to copy and paste them in Android Studio as it won’t run on the IDE!

Step By Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.

Step 2: Creating New Fragments

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

Swipe Navigation in Android

 

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




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


Kotlin




import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
  
class Fragment1 : Fragment() {
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_1, container, false)
    }
}


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 correspond to the libraries which we import.
  • We name our Fragment Fragment1.
  • Fragment1 displays the layout fragment_1.xml which we will make now.

Step 3: Creating New Layouts for Fragments

Each Fragment needs to display a layout. We can design this layout anyhow we want. Here is the code for how we would implement this layout as:  

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    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:textColor="#81c784"
        android:textSize="20sp" />
</LinearLayout>


This looks like:

Swipe Navigation in Android

 

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

Step 4: Creating New FragmentPageAdapter

Now that we have all our three Fragments and three layouts 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




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


Kotlin




import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
  
class SimpleFragmentPagerAdapter(fm: FragmentManager?) : FragmentPagerAdapter(fm!!) {
    override fun getItem(position: Int): Fragment {
        return when (position) {
            0 -> {
                Fragment1()
            }
            1 -> {
                Fragment2()
            }
            else -> {
                Fragmnet3()
            }
        }
    }
  
    override fun getCount(): Int {
        return 3
    }
}


Explanation:

  • The getItem() method returns the Fragment at the 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 5: Working with MainActivity and activity_main.xml

Now that we have everything ready, the last step is just to make our MainActivity 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 look like this:

XML




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


Java




import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
  
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);
    }
}


Kotlin




import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.viewpager.widget.ViewPager
  
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        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
        val viewPager = findViewById<ViewPager>(R.id.viewpager) 
        // Create an adapter that knows which fragment should be shown on each page
        val adapter = SimpleFragmentPagerAdapter(supportFragmentManager)
        // Set the adapter onto the view pager
        viewPager.adapter = adapter
    }
}


Output:



Next Article

Similar Reads

Practice Tags :
three90RightbarBannerImg