Open In App

Parallax Effect in Android with Example

Improve
Improve
Like Article
Like
Save
Share
Report

In recent years, every Android application has prioritized user experience. A well-designed app will have high user ratings and popularity. Many effects are available in the UI/UX space to provide users with a good experience. Parallax is one such effect. Let’s take a look at what this is all about, as well as a sample app to see how it works.

What exactly is parallax?

The term “parallax” sounds like a mathematical term. Yes, this technique is derived from a mathematical principle. It’s a technique used in computer graphics and web design in which background images move faster than foreground images, creating the illusion of depth in a 2D scene and increasing immersion. Parallax scrolling can be a really interesting technique for giving parts of your app more life and character. It is not limited to Android/web apps. Most gaming applications use this effect to create the illusion of objects moving backward with only one object in focus. Material design scroll animations will include parallax in Android. A parallax scroll effect with a header image is used in some designs.

Using the Parallax Effect in an Android App

  1. Let’s start by making a new project.
  2. Begin a new Android project.
  3. Next, choose Empty Activity and Next Name: Parallax Name of the Android package: com.geeksforgeeks.example.parallax
  4. Kotlin is the language.
  5. Finish

Let’s add the necessary dependencies.

implementation "androidx.coordinatorlayout:coordinatorlayout:1.1.0"
implementation 'androidx.recyclerview:recyclerview:1.1.1'
implementation 'com.google.android.material:material:1.2.0-alpha05'

In this section, we will create an app that will display a list of books with a parallax scrolling effect. Let us begin with the XML layout. To begin, we’ll need a collapsing toolbar layout that we can add to the main activity XML. A collapsing toolbar layout is analogous to a FrameLayout. Whatever elements were added most recently will be placed at the top. This positioning is critical for parallax to work properly.

Let’s start with the skeleton of the activity main.xml and then add the required element code later.

<androidx.coordinatorlayout.widget.CoordinatorLayout>
<com.google.android.material.appbar.AppBarLayout>
    <com.google.android.material.appbar.CollapsingToolbarLayout>
        <ImageView/>
        <android.appcompat.widget.Toolbar />
        <com.google.android.material.tabs.TabLayout/>
    </com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager/>
</androidx.coordinatorlayout.widget.CoordinatorLayout> 

Our activity main.xml file will look like this:

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".GfgMainActivity">
  
    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:fitsSystemWindows="true">
  
        <include layout="@layout/toolbar"/>
  
        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabGravity="fill"
            app:tabTextAppearance="@style/TextAppearance.AppCompat.Medium"
            app:tabSelectedTextColor="@android:color/black"
            app:tabBackground="@android:color/holo_orange_dark"
            app:tabTextColor="@android:color/white"
            app:tabIndicatorColor="@android:color/white"
            app:tabMode="fixed" />
  
    </com.google.android.material.appbar.AppBarLayout>
  
    <androidx.gfgViewPager.widget.GfgViewPager
        android:id="@+id/gfgViewPager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="17dp"
        app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior"/>
  
</androidx.coordinatorlayout.widget.CoordinatorLayout>


Please take note that the following attributes have been added to the above layout:

To use with the CollapsingToolbarLayout:

app:layout scrollFlags="scroll|exitUntilCollapsed"

Regarding the ImageView:

app:layout scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"
app:layout collaps"
Mode="parallax"

In relation to the Toolbar:

app:layout scrollFlags="scroll|enterAlways"

In our MainActivity, we must configure the Viewpager and tabs. Because we’ve included tabs in our layout, we’ll need a ViewPager to make it work. In addition, we will create a Fragment that loads the RecyclerView and an adapter that loads the items in the RecyclerView. In the activity, I am in charge of configuring the view pager and tabs, as well as loading the fragment for the viewpager. I’m loading three tabs and one fragment here. These attributes are defined in the ScreenSlidePagerAdapter.

Kotlin




class GfgMainActivity : FragmentActivity() {
    private lateinit var gfgGfgViewP: GfgViewP
    private lateinit var gfgTabLayout : GfgTabLayout
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        gfgGfgViewP = findViewById(R.id.gfgViewP)
        gfgTabLayout = findViewById(R.id.theTabs)
        gfgTabLayout.setupWithGfgViewP(gfgGfgViewP)
  
        val pagerAdapter = ScreenSlidePagerAdapter(supportFragmentManager)
        gfgGfgViewP.adapter = pagerAdapter
    }
  
    override fun onBackPressed() {
        if (gfgGfgViewP.currentItem == 0) {
            // If the user is currently looking at the 
            // first step, allow the system to handle the
            // Back button. This calls finish() on this 
            // activity and pops the back stack.
            super.onBackPressed()
        } else {
            // Otherwise, select the previous step.
            gfgGfgViewP.currentItem = gfgGfgViewP.currentItem - 1
        }
    }
  
    private inner class ScreenSlidePagerAdapter(fm: FragmentManager) :
        FragmentStatePagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
        override fun getCount(): Int = 3
        override fun getItem(position: Int): Fragment = BooksFragment().newInstance()
        override fun getPageTitle(position: Int): CharSequence? {
            var title  = ""
            when(position) {
                0 -> title ="Android"
                1 -> title = "DSA"
                2 -> title = "Interviews"
            }
            return title
        }
    }
}


Make a CoursesFragment that will load the Recyclerview.

Kotlin




class CoursesFragment : Fragment() {
    fun newInstance(): CoursesFragment {
        return CoursesFragment()
    }
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view : View? = inflater.inflate(R.layout.courses_fragment, container, false)
        val rvCourses : RecyclerView = view!!.findViewById(R.id.courseList)
        rvCourses.layoutManager = LinearLayoutManager(activity);
        val recyclerAdapter = CoursesRecyclerAdapter(Util().getCourses())
        rvCourses.adapter = recyclerAdapter
        return view
    }
}


Output:

Set the scroll speed and other attributes in the ImageView of the toolbar layout to customize them. To summarise, the Android support library contains a plethora of such utilities that assist us in making our app better in every way. We need to investigate them and use them to create more usable apps.



Last Updated : 28 Jan, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads