Android Compose – Set Width for Text
To set width for Text composable, in Android Jetpack Compose, assign modifier parameter of Text with Modifier companion object, where width() method is called on the Modifier. Pass required width value in the width() function call.
The following is a sample code snippet to set the width of Text composable.
import androidx.compose.foundation.layout.width
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
Text(
"Hello World",
modifier = Modifier.width(150.dp)
)
Make sure to import width, Modifier and dp.
Example
Create an Android Application with Jetpack Compose as template, and modify MainActivity.kt as shown in the following.
In the following activity, the width of Text composable is set to 150dp.
MainActivity.kt
package com.example.myapplication
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.width
import androidx.compose.material.Text
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
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 {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxWidth()
) {
Text(
"Hello World! This is a sample text",
modifier = Modifier.width(150.dp)
)
}
}
}
}
}
Screenshot in Emulator
Let us define two Text composables, with different width values.
MainActivity.kt
package com.example.myapplication
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.layout.*
import androidx.compose.material.Text
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
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 {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxWidth()
) {
Text(
"Hello World! This is a sample text with 150dp width.",
modifier = Modifier.width(150.dp)
)
Spacer(modifier = Modifier.size(20.dp))
Text(
"Hello World! This is a sample text with 250dp width.",
modifier = Modifier.width(250.dp)
)
}
}
}
}
}
Screenshot in Emulator
Conclusion
In this Android Jetpack Compose Tutorial, we learned how to set width for Text composable in Android Project with Jetpack Compose.