SyntaxStudy
Sign Up
Kotlin Android with Kotlin: Activities and ViewBinding
Kotlin Beginner 1 min read

Android with Kotlin: Activities and ViewBinding

Kotlin is the official language for Android development, and Android Studio generates Kotlin by default for new projects. Activities are the entry points to Android apps; each activity has a lifecycle (onCreate, onStart, onResume, onPause, onStop, onDestroy) that the system manages. ViewBinding replaces the error-prone findViewById pattern with a generated binding class whose properties correspond directly to view IDs in the layout XML. Enabling it in the module's build.gradle.kts adds zero runtime overhead; all binding happens at build time. Android KTX (Kotlin Extensions) is a set of Kotlin extension functions for the Android framework that makes common tasks more idiomatic: replacing Toast.makeText(...).show() with toast(), simplifying bundle creation, and adding lifecycle-aware coroutine scopes.
Example
// build.gradle.kts (app module)
// android { buildFeatures { viewBinding = true } }

// MainActivity.kt
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import com.example.app.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.btnGreet.setOnClickListener {
            val name = binding.etName.text.toString().trim()
            if (name.isEmpty()) {
                Toast.makeText(this, "Enter a name", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            binding.tvResult.text = "Hello, $name!"
        }

        // Coroutine tied to Activity lifecycle
        lifecycleScope.launch {
            val data = fetchDataSuspend()
            binding.tvResult.text = data
        }
    }

    private suspend fun fetchDataSuspend(): String {
        kotlinx.coroutines.delay(1000)
        return "Data loaded!"
    }
}