How to add a Slider in Android Jetpack Compose

By Mohammed Rashid •  November 19th, 2022 • 

Slider is a UI component that helps users to choose a range between two fixed values. Let’s learn how to create a simple Slider component in Jetpack compose.

The Slider function in compose helps to create a slider with a range. We can get the desired result by utilizing its parameters such as value, onValueChange, valueRange, etc. See the code snippet given below.

@Composable
fun SliderExample() {
    var position by remember { mutableStateOf(0f) }
    Slider(
        modifier = Modifier.padding(20.dp),
        value = position,
        onValueChange = { position = it },
        valueRange = 0f..10f,
        onValueChangeFinished = {
            // do something
        },
        steps = 5,
    )
}

The variable position holds the current value of the slider. You can customize steps by changing the steps parameter.

Following is the output.

slider jetpack compose

The complete code is given below for reference.

package com.example.myapplication

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.myapplication.ui.theme.MyApplicationTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApplicationTheme {
                Surface(
                    color = MaterialTheme.colors.background,
                    modifier = Modifier.fillMaxSize()
                ) {
                    SliderExample()
                }
            }
        }
    }
}

@Composable
fun SliderExample() {
    var position by remember { mutableStateOf(0f) }
    Slider(
        modifier = Modifier.padding(20.dp),
        value = position,
        onValueChange = { position = it },
        valueRange = 0f..10f,
        onValueChangeFinished = {
            // do something
        },
        steps = 5,
    )
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    MyApplicationTheme {
        SliderExample()
    }
}

I hope this tutorial on the Jetpack Compose slider is helpful for you.

Keep Reading