Open In App

Spacer in Android Jetpack Compose

Last Updated : 04 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Jetpack Compose, a Spacer is a blank element that is used to create a Space between two UI elements. Suppose, we have created Element 1 and we want to place Element 2 below Element 1 but with a top margin, we can declare a Spacer between the two elements.

space-compose


So in this article, we will show you how you could implement a Spacer 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 or Empty Activity. If you do not find this template, try upgrading the Android Studio to the latest version.

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.

MainActivity.kt:

Kotlin
package com.geeksforgeeks.demo

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.*
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.*

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MaterialTheme {
                SpacerDemonstration()
            }
        }
    }
}

// create a composable function
@Composable
fun SpacerDemonstration(){
    Column(
        Modifier.fillMaxWidth().absolutePadding(10.dp, 100.dp, 10.dp, 0.dp), horizontalAlignment = Alignment.CenterHorizontally) {

        // Creating Button 1
        Button(onClick = { /*TODO*/ },
            colors = ButtonDefaults.buttonColors(containerColor = Color(0XFF0F9D58)),
        ) {
            Text("Button 1", color = Color.White)
        }

        // Adding a Spacer of height 20dp
        Spacer(modifier = Modifier.height(20.dp))

        // Creating Button 2
        Button(onClick = { /*TODO*/ },
            colors = ButtonDefaults.buttonColors(containerColor = Color(0XFF0F9D58)),
        ) {
            Text("Button 2", color = Color.White)
        }

        // Adding a Spacer of height 200dp
        Spacer(modifier = Modifier.height(200.dp))

        // Adding a Text
        Text(text = "Hello Geek!", fontSize = 50.sp)
    }
}

Output:

You can see that Button 1 and Button 2 are separated by 20dp and Button 2 and Text are separated by 200dp.

spacer-compose



Next Article
Article Tags :

Similar Reads