Open In App

How to Create Swipe Navigation in Android?

Last Updated : 30 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
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. ViewPager2: ViewPager2 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 ViewPager2 using the setAdapter() method. The adapter which we set is called FragmentStateAdapter which is an abstract class in Java. Hence, we create our own SampleFragmentStateAdapter which extends from FragmentStateAdapter and displays our Fragments on the screen. When we launch the app in our device, the ViewPager2 asks the SampleFragmentPagerAdapter how many pages are there to swipe through. The getItemCount() method of the adapter returns this answer to the ViewPager2. Then the ViewPager2 asks for the Fragment which is at the 0th position and the adapter returns that particular fragment which is then displayed by ViewPager2 on our screen. When we swipe left, ViewPager2 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)   

Create-new-fragment


We can create as many Fragments as we want but since we will be displaying only three screens, hence we will create three Fragments. 

Step 3: Working with fragments

Now we will open our Fragments and copy this code over there

Fragment1.java
package org.geeksforgeeks.demo;

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);
    }
}
Fragment1.kt

Explanation:   

  • We name our Fragment Fragment1, Fragment2, and Fragment3
  • They display the layouts fragment_1.xml, fragment_2.xml and fragment_3.xml respectively which we will make now.

Step 4: 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:  

fragment_1.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"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:gravity="center"
    android:background="@color/white"
    android:padding="16dp"
    tools:context=".Fragment1">

    <ImageView
        android:layout_width="250dp"
        android:layout_height="200dp"
        android:src="@drawable/gfg_logo" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:gravity="center"
        android:text="@string/gfg_text"
        android:textColor="@color/black"
        android:textSize="20sp" />
</LinearLayout>

This looks like:

sample-fragment

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

Step 5: Creating New FragmentStateAdapter

Now that we have all our three Fragments and three layouts associated with each one of them, we will now build our FragmentStateAdapter and call it SimpleFragmentStateAdapter. This can be done by first creating a new Java/Kotlin class and naming it as SimpleFragmentStateAdapter. Here’s the code it will contain:  

SimpleFragmentStateAdapter.java
package org.geeksforgeeks.demo;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;

public class SimpleFragmentStateAdapter extends FragmentStateAdapter {

    public SimpleFragmentStateAdapter(@NonNull FragmentActivity fragmentActivity) {
        super(fragmentActivity);
    }

    @Override
    public int getItemCount() {
        return 3;
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        switch (position) {
            case 0:
                return new Fragment1();
            case 1:
                return new Fragment2();
            default:
                return new Fragment3();
        }
    }
}
SimpleFragmentStateAdapter.kt

Explanation:

  • The createFragment() 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 getItemCount() method returns the number of Fragments there are to be displayed, which, in this case, is three.

Step 6: 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:

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>


Mainactivity File:

MainActivity.java
package org.geeksforgeeks.demo;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Find the ViewPager2 in the layout
        ViewPager2 viewPager = findViewById(R.id.viewpager);

        // Create the adapter
        SimpleFragmentStateAdapter adapter = new SimpleFragmentStateAdapter(this);

        // Attach the adapter to the ViewPager
        viewPager.setAdapter(adapter);
    }
}
MainActivity.kt

Output:



Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg