Android Compose – Center Align Content in Row
To center align/arrange content (composables) inside Row, set horizontalAlignment
argument of this Row composable function with Arrangement.Center
.
The following code snippet shows how to align the contents of this Row to its center.
Row(
horizontalArrangement = Arrangement.Center
) {
...
}
Example
In this example, let us display a Row composable. Inside Row composable, we will have two Box composables. We shall align the composables inside this Row composable towards the center.
To demonstrate the alignment towards the end, we shall make the Row to fill the maximum width of the screen, and set specific size for the Box composables inside Row. Therefore, when we align content of this Row to the center, there would be a gap left at the starting and the ending of this Row.
Create a Project in Android Studio with Empty Compose Activity template, and modify MainActivity.kt file as shown in the following.
MainActivity.kt
package com.example.myapplication
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.example.myapplication.ui.theme.MyApplicationTheme
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApplicationTheme {
Row(modifier = Modifier
.padding(20.dp)
.fillMaxWidth()
.background(Color.Gray),
horizontalArrangement = Arrangement.Center,
) {
Box(Modifier.size(100.dp).padding(10.dp).background(Color.Yellow))
Box(Modifier.size(100.dp).padding(10.dp).background(Color.Yellow))
}
}
}
}
}
Screenshot
Conclusion
In this Android Jetpack Compose Tutorial, we learned how to align contents of a Row composable to the center.