1. Home
  2. /
  3. Jetpack-compose
  4. /
  5. Jetpack Compose Counter With Alert

Jetpack Compose Counter With Alert - Jetpack-compose Typing CST Test

Loading…

Jetpack Compose Counter With Alert — Jetpack-compose Code

Counter shows a Snackbar alert when it reaches 10.

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {
	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		setContent {
		AlertCounterApp()
		}
	}
}

@Composable
fun AlertCounterApp() {
	var count by remember { mutableStateOf(0) }
	val scaffoldState = rememberScaffoldState()
	val scope = rememberCoroutineScope()
	Scaffold(scaffoldState = scaffoldState) {
		Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {
		Text("Counter: $count", style = MaterialTheme.typography.h4)
		Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
		Button(onClick = {
		count++
		if(count == 10) scope.launch { scaffoldState.snackbarHostState.showSnackbar("Count reached 10!") }
		}) { Text("+") }
		Button(onClick = { count = 0 }) { Text("Reset") }
		}
		}
	}
}

Jetpack-compose Language Guide

Jetpack Compose is Android’s modern toolkit for building native UI using Kotlin, offering a declarative approach to designing app interfaces and simplifying UI development for Android.

Primary Use Cases

  • ▸Native Android app development
  • ▸Apps requiring reactive UI updates
  • ▸Modernizing legacy Android apps
  • ▸Enterprise Android apps with dynamic content
  • ▸Rapid prototyping of Android interfaces

Notable Features

  • ▸Declarative UI design in Kotlin
  • ▸Composable functions for reusable UI elements
  • ▸Integration with ViewModel and LiveData/StateFlow
  • ▸Material Design components and theming
  • ▸Hot reload and fast preview in Android Studio

Origin & Creator

Developed by Google and introduced in 2019 to modernize Android UI development with a declarative approach using Kotlin.

Industrial Note

Jetpack Compose is widely used for modern Android apps, enterprise applications, and apps that require dynamic UI updates and reactive components.

More Jetpack-compose Typing Exercises

Jetpack Compose Simple Todo AppJetpack Compose Counter AppJetpack Compose Dark Mode CounterJetpack Compose Multi CounterJetpack Compose Auto Increment CounterJetpack Compose Todo With PriorityJetpack Compose Countdown Timer

Practice Other Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypher