Jetpack Compose - A Hello World App
Default App
When you finish the setup, create a project, by default you will get a simple app, with a Screen of White background that simply displays Hello Android in the top corner. Also, as I have mentioned earlier, you can see that there is no layout file. in mainactivity.kt itself, we are setting up our content, that should be displayed on the Screen.
But to understand the code Better, let's remove everything and Write from scratch.
Coding a Hello World App
After erasing everything from our mainactivity file, we will now import some libraries that we need to render even the basic UI.
package com.example.testapp
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
We have imported our package, Activity and some compose functions to setContent and display text.
Next, we need a main activity , which will be a ComponenetActivity, we will have our onCreate method which will call setContent, that will set content on the screen.
package com.example.testapp
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
// HERE
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
}
}
}
We can now call the Text function from material and pass some String as text parameter , which will be displayed as it is on the Screen.
setContent {
Text(text = "Hello World")
}
This will render a simple app, that displays Hello World on the top corner. Now you can clap 👏👏👏 for yourself, for successfully Crossing the 0th step 🤞😁 in programming.
Centering Text Content
But, Let's just take a step further and try to center our Text content.😎 We will use the Box composable Layout to fill the entire space and then align our text to the center.So we will first import the needed packages and Pay attention to the Import path.
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
// The modifier should come from compose
// unlike this
// import java.lang.reflect.Modifier
import androidx.compose.ui.Modifier
import androidx.compose.ui.Alignment
We will then simply wrap our text content with the Box and give it a fillMaxSize modifier and set the alignment to center.
setContent {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(text = "Hello World")
}
}
And that's it. Run your app again and you will find a Hello world at the center. That's how simpler things can get with Jetpack Compose. Saty tuned for more tutorials 😇