0
0
Android Kotlinmobile~5 mins

Activity concept in Android Kotlin

Choose your learning style9 modes available
Introduction

An Activity is like a single screen in an app. It shows the user what to see and lets them interact with the app.

When you want to show a new screen to the user.
When you need to handle user actions on a screen.
When you want to switch between different parts of your app.
When you want to display a form or information page.
When you want to manage the app's lifecycle for a screen.
Syntax
Android Kotlin
class MainActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
  }
}

onCreate() is where you set up the screen.

setContentView() links the screen to a layout file.

Examples
This creates a second screen with its own layout.
Android Kotlin
class SecondActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_second)
  }
}
onStart() runs when the screen is about to be shown.
Android Kotlin
override fun onStart() {
  super.onStart()
  // Code to run when activity becomes visible
}
Sample App

This simple Activity shows a text message on the screen.

Android Kotlin
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.widget.TextView

class MainActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val textView = TextView(this)
    textView.text = "Hello from Activity!"
    setContentView(textView)
  }
}
OutputSuccess
Important Notes

Every screen in Android is an Activity or uses one.

Activities have a lifecycle: onCreate, onStart, onResume, onPause, onStop, onDestroy.

Use the AndroidManifest.xml to declare your Activity.

Summary

An Activity is a screen in your app.

Use onCreate() to set up the screen.

Activities manage user interaction and app flow.