How to add Scrolling in Android Jetpack Compose

By Mohammed Rashid •  September 2nd, 2022 • 

There are two scroll modifiers that allow basic scrolling in Jetpack Compose- verticalScroll and horizontalScroll. As the name indicates, verticalScroll helps to scroll vertically whereas horizontalScroll helps to scroll horizontally.

See the code snippet given below.

@Composable
fun ScrollItems() {
    Column(
        modifier = Modifier
            .verticalScroll(rememberScrollState())
    ) {
        repeat(20) {
            Text("Item $it", modifier = Modifier.padding(20.dp))
        }
    }
}

Here, you can see 20 list items that can be scrolled vertically. See the complete scrolling example given below.

package com.example.example
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.example.ui.theme.ExampleTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ExampleTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    ScrollItems()
                }
            }
        }
    }
}

@Preview(showBackground = true)
@Composable
fun ScrollItems() {
    Column(
        modifier = Modifier
            .verticalScroll(rememberScrollState())
    ) {
        repeat(20) {
            Text("Item $it", modifier = Modifier.padding(20.dp))
        }
    }
}


@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    ExampleTheme {
        ScrollItems()
    }
}

You get the output as given below.

That’s how you add basic scrolling in Jetpack Compose.

Mohammed Rashid

Keep Reading