CPS251 Android Development by Scott Shaper

Building the MainActivity

The MainActivity is the entry point of the application. It is the first screen that the user sees when they open the app. It is responsible for setting up the Compose UI and managing the ViewModel. For this application the MainActivity just calls the NoteScreen composable and passes the ViewModel to it.


// MainActivity is the entry point of the Android application.
class MainActivity : ComponentActivity() {
    // onCreate is called when the activity is first created.
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // Configure the window to use light status bar icons for a modern look.
        WindowCompat.getInsetsController(window, window.decorView).isAppearanceLightStatusBars = true

        // Initialize the ViewModel using by viewModels.
        // The provideFactory method ensures the ViewModel has access to the application context.
        val viewModel: NoteViewModel by viewModels {
            NoteViewModel.provideFactory(application)
        }

        // Set up the Compose UI content for this activity.
        setContent {
            // Apply the custom theme for the application.
            MaterialTheme {
                // Surface is a fundamental composable that applies background color and fills the screen.
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    // Display the NoteScreen, passing the initialized ViewModel to it.
                    NoteScreen(viewModel)
                }
            }
        }
    }
}