'How to center (horizontally and vertically) text in Jetpack Compose Text
I have a large Text.
Text(
text = "Select Bank account",
color = Color.White,
fontSize = 18.sp,
textAlign = TextAlign.Center,
modifier = Modifier
.background(Color.Black)
.fillMaxSize()
.padding(16.dp)
.align(Alignment.CenterHorizontally)
)
How to center the text both vertically and horizontally?
In a view-based system, we can achieve this using Gravity.CENTER.
Looking for a similar solution.
Note
Looking for a solution without using another component wrapping the text. (Box, Column, etc).
I am aware that my requirement can be achieved using a wrapper component as shown here.
Solution 1:[1]
Put the text in a box and set contentAlignment of the Box to center.
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center){
Text(
text = "Select Bank account",
color = Color.White,
fontSize = 18.sp,
textAlign = TextAlign.Center,
modifier = Modifier
.background(Color.Black)
.padding(16.dp)
.align(Alignment.Center)
)
}
Solution 2:[2]
You can achieve this by adding similar xml attribute like "wrap_content" as height in compose too.
Add "wrapContentHeight()" to modifier and you will get it to align to centre of the page.
Text(
text = "Select Bank account",
color = Color.White,
fontSize = 18.sp,
textAlign = TextAlign.Center,
modifier = Modifier
.background(Color.Black)
.fillMaxSize()
.wrapContentHeight()
.padding(16.dp)
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rafsanjani |
| Solution 2 | sHaRkBoY |

