In Android, the Scrollable Modifier detects the scroll gestures but does not offset its contents. Jetpack Compose supports nested scrolling, in which multiple elements react to a single scroll gesture. A typical example of nested scrolling is a list inside another list.
In this article, we will show you how you could create Nested Scrolling in Android using Jetpack Compose. Follow the below steps once the IDE is ready.
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. While choosing the template, select Empty Compose Activity. If you do not find this template, try upgrading the Android Studio to the latest version. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
package com.geeksforgeeks.jcnestedscrolling
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super .onCreate(savedInstanceState)
setContent {
// Creating a Simple Scaffold
// Layout for the application
Scaffold(
// Creating a Top Bar
topBar = { TopAppBar(title = { Text( "GFG | Nested Scrolling" , color = Color.White) }, backgroundColor = Color( 0xff0f9d58 )) },
// Creating Content
content = {
// Creating a Column Layout
Column(Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
// Creating a Scrollable Box
Box(modifier = Modifier.background(Color.LightGray).verticalScroll(rememberScrollState()).padding( 32 .dp)) {
Column {
// Create 6 Scrollable Boxes
repeat( 6 ) {
Box(modifier = Modifier.height( 128 .dp).verticalScroll(rememberScrollState())) {
// Creating a Text in each Box
Text(
"Scroll here" ,
modifier = Modifier
.border( 12 .dp, Color.DarkGray)
.padding( 24 .dp)
.height( 150 .dp)
)
}
}
}
}
}
}
)
}
}
} |
Output:
You can see that we are able to implement nested scrolling in our application.