content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.woof import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.compose.animation.animateColorAsState import androidx.compose.animation.animateContentSize import androidx.compose.animation.core.Spring import androidx.compose.animation.core.spring import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ExpandLess import androidx.compose.material.icons.filled.ExpandMore import androidx.compose.material3.Card import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import com.example.woof.data.Dog import com.example.woof.data.dogs import com.example.woof.ui.theme.WoofTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { WoofTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize() ) { WoofApp() } } } } } /** * Composable that displays an app bar and a list of dogs. */ @Composable fun WoofApp() { Scaffold( topBar = { WoofTopAppBar() } ) { LazyColumn(contentPadding = it) { items(dogs) { DogItem( dog = it, modifier = Modifier.padding(dimensionResource(id = R.dimen.padding_small)) ) } } } } /** * Composable that displays a list item containing a dog icon and their information. * * @param dog contains the data that populates the list item * @param modifier modifiers to set to this composable */ @Composable fun DogItem( dog: Dog, modifier: Modifier = Modifier ) { var expanded by remember { mutableStateOf(false) } val color by animateColorAsState( targetValue = if (expanded) MaterialTheme.colorScheme.tertiaryContainer else MaterialTheme.colorScheme.primaryContainer, label = "" ) Card(modifier = modifier) { Column( modifier = Modifier .animateContentSize( animationSpec = spring( dampingRatio = Spring.DampingRatioNoBouncy, stiffness = Spring.StiffnessMedium ) ) .background(color = color) ) { Row( modifier = Modifier .fillMaxWidth() .padding(dimensionResource(R.dimen.padding_small)) ) { DogIcon(dog.imageResourceId) DogInformation(dog.name, dog.age) Spacer(modifier = Modifier.weight(1f)) DogItemButton( expanded = expanded, onClick = { expanded = !expanded } ) } if (expanded) { DogHobby( dogHobby = dog.hobbies, modifier.padding( start = dimensionResource(id = R.dimen.padding_medium), top = dimensionResource(id = R.dimen.padding_small), end = dimensionResource(id = R.dimen.padding_medium), bottom = dimensionResource(id = R.dimen.padding_medium) ) ) } } } } /** * Composable that displays a photo of a dog. * * @param dogIcon is the resource ID for the image of the dog * @param modifier modifiers to set to this composable */ @Composable fun DogIcon( @DrawableRes dogIcon: Int, modifier: Modifier = Modifier ) { Image( modifier = modifier .size(dimensionResource(R.dimen.image_size)) .padding(dimensionResource(R.dimen.padding_small)) .clip(MaterialTheme.shapes.small), painter = painterResource(dogIcon), contentScale = ContentScale.Crop, // Content Description is not needed here - image is decorative, and setting a null content // description allows accessibility services to skip this element during navigation. contentDescription = null ) } /** * Composable that displays a dog's name and age. * * @param dogName is the resource ID for the string of the dog's name * @param dogAge is the Int that represents the dog's age * @param modifier modifiers to set to this composable */ @Composable fun DogInformation( @StringRes dogName: Int, dogAge: Int, modifier: Modifier = Modifier ) { Column(modifier = modifier) { Text( text = stringResource(dogName), style = MaterialTheme.typography.displayMedium, modifier = Modifier.padding(top = dimensionResource(R.dimen.padding_small)) ) Text( text = stringResource(R.string.years_old, dogAge), style = MaterialTheme.typography.bodyLarge ) } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun WoofTopAppBar(modifier: Modifier = Modifier) { CenterAlignedTopAppBar( title = { Row(verticalAlignment = Alignment.CenterVertically) { Image( modifier = Modifier .size(dimensionResource(id = R.dimen.image_size)) .padding(dimensionResource(id = R.dimen.padding_small)), painter = painterResource(id = R.drawable.ic_woof_logo), contentDescription = null ) Text( text = stringResource(id = R.string.app_name), style = MaterialTheme.typography.displayLarge ) } }, modifier = modifier ) } @Composable fun DogItemButton( expanded: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier ) { IconButton( onClick = { onClick.invoke() }, modifier = modifier ) { Icon( imageVector = if (expanded) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore, contentDescription = null, tint = MaterialTheme.colorScheme.secondary ) } } @Composable fun DogHobby( @StringRes dogHobby: Int, modifier: Modifier = Modifier ) { Column(modifier = modifier) { Text( text = stringResource(id = R.string.about), style = MaterialTheme.typography.labelSmall ) Text( text = stringResource(id = dogHobby), style = MaterialTheme.typography.bodyLarge ) } } /** * Composable that displays what the UI of the app looks like in light theme in the design tab. */ @Preview(showBackground = true) @Composable fun WoofPreview() { WoofTheme(darkTheme = false) { WoofApp() } } @Preview(showBackground = true) @Composable fun WoofDarkPreview() { WoofTheme(darkTheme = true) { WoofApp() } }
AndroidLearning/compose-training-woof/app/src/main/java/com/example/woof/MainActivity.kt
1826594654
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.woof.data import androidx.annotation.DrawableRes import androidx.annotation.StringRes import com.example.woof.R /** * A data class to represent the information presented in the dog card */ data class Dog( @DrawableRes val imageResourceId: Int, @StringRes val name: Int, val age: Int, @StringRes val hobbies: Int ) val dogs = listOf( Dog(R.drawable.koda, R.string.dog_name_1, 2, R.string.dog_description_1), Dog(R.drawable.lola, R.string.dog_name_2, 16, R.string.dog_description_2), Dog(R.drawable.frankie, R.string.dog_name_3, 2, R.string.dog_description_3), Dog(R.drawable.nox, R.string.dog_name_4, 8, R.string.dog_description_4), Dog(R.drawable.faye, R.string.dog_name_5, 8, R.string.dog_description_5), Dog(R.drawable.bella, R.string.dog_name_6, 14, R.string.dog_description_6), Dog(R.drawable.moana, R.string.dog_name_7, 2, R.string.dog_description_7), Dog(R.drawable.tzeitel, R.string.dog_name_8, 7, R.string.dog_description_8), Dog(R.drawable.leroy, R.string.dog_name_9, 4, R.string.dog_description_9) )
AndroidLearning/compose-training-woof/app/src/main/java/com/example/woof/data/Dog.kt
762462049
package com.example.tiptime import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performTextInput import com.example.tiptime.ui.theme.TipTimeTheme import org.junit.Rule import org.junit.Test import java.text.NumberFormat class TipUITest { @get:Rule val composeTestRule = createComposeRule() @Test fun calculate_20_percent_tip() { composeTestRule.setContent { TipTimeTheme { TipTimeLayout() } } composeTestRule.onNodeWithText("Bill Amount").performTextInput("10") composeTestRule.onNodeWithText("Tip Percentage").performTextInput("20") val expectedTip=NumberFormat.getCurrencyInstance().format(2) composeTestRule.onNodeWithText("Tip Amount: $expectedTip").assertExists( "No node with this text was found.") } }
AndroidLearning/compose-training-tip-calculator/app/src/androidTest/java/com/example/tiptime/TipUITest.kt
1232698491
package com.example.tiptime import org.junit.Assert.assertEquals import org.junit.Test import java.text.NumberFormat class TipCalculatorTest { @Test fun calculateTip_20PercentNoRoundup(){ val amount = 10.00 val tipPercent = 20.00 val expectedTip = NumberFormat.getCurrencyInstance().format(2) val actualTip = calculateTip(amount = amount, tipPercent = tipPercent, false) assertEquals(expectedTip, actualTip) } }
AndroidLearning/compose-training-tip-calculator/app/src/test/java/com/example/tiptime/TipCalculatorTest.kt
1361900309
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.tiptime.ui.theme import androidx.compose.ui.graphics.Color val md_theme_light_primary = Color(0xFF984061) val md_theme_light_onPrimary = Color(0xFFFFFFFF) val md_theme_light_primaryContainer = Color(0xFFFFD9E2) val md_theme_light_onPrimaryContainer = Color(0xFF3E001D) val md_theme_light_secondary = Color(0xFF754B9C) val md_theme_light_onSecondary = Color(0xFFFFFFFF) val md_theme_light_secondaryContainer = Color(0xFFF1DBFF) val md_theme_light_onSecondaryContainer = Color(0xFF2D0050) val md_theme_light_tertiary = Color(0xFF984060) val md_theme_light_onTertiary = Color(0xFFFFFFFF) val md_theme_light_tertiaryContainer = Color(0xFFFFD9E2) val md_theme_light_onTertiaryContainer = Color(0xFF3E001D) val md_theme_light_error = Color(0xFFBA1A1A) val md_theme_light_errorContainer = Color(0xFFFFDAD6) val md_theme_light_onError = Color(0xFFFFFFFF) val md_theme_light_onErrorContainer = Color(0xFF410002) val md_theme_light_background = Color(0xFFFAFCFF) val md_theme_light_onBackground = Color(0xFF001F2A) val md_theme_light_surface = Color(0xFFFAFCFF) val md_theme_light_onSurface = Color(0xFF001F2A) val md_theme_light_surfaceVariant = Color(0xFFF2DDE2) val md_theme_light_onSurfaceVariant = Color(0xFF514347) val md_theme_light_outline = Color(0xFF837377) val md_theme_light_inverseOnSurface = Color(0xFFE1F4FF) val md_theme_light_inverseSurface = Color(0xFF003547) val md_theme_light_inversePrimary = Color(0xFFFFB0C8) val md_theme_light_surfaceTint = Color(0xFF984061) val md_theme_light_outlineVariant = Color(0xFFD5C2C6) val md_theme_light_scrim = Color(0xFF000000) val md_theme_dark_primary = Color(0xFFFFB0C8) val md_theme_dark_onPrimary = Color(0xFF5E1133) val md_theme_dark_primaryContainer = Color(0xFF7B2949) val md_theme_dark_onPrimaryContainer = Color(0xFFFFD9E2) val md_theme_dark_secondary = Color(0xFFDEB7FF) val md_theme_dark_onSecondary = Color(0xFF44196A) val md_theme_dark_secondaryContainer = Color(0xFF5C3382) val md_theme_dark_onSecondaryContainer = Color(0xFFF1DBFF) val md_theme_dark_tertiary = Color(0xFFFFB1C7) val md_theme_dark_onTertiary = Color(0xFF5E1132) val md_theme_dark_tertiaryContainer = Color(0xFF7B2948) val md_theme_dark_onTertiaryContainer = Color(0xFFFFD9E2) val md_theme_dark_error = Color(0xFFFFB4AB) val md_theme_dark_errorContainer = Color(0xFF93000A) val md_theme_dark_onError = Color(0xFF690005) val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6) val md_theme_dark_background = Color(0xFF001F2A) val md_theme_dark_onBackground = Color(0xFFBFE9FF) val md_theme_dark_surface = Color(0xFF001F2A) val md_theme_dark_onSurface = Color(0xFFBFE9FF) val md_theme_dark_surfaceVariant = Color(0xFF514347) val md_theme_dark_onSurfaceVariant = Color(0xFFD5C2C6) val md_theme_dark_outline = Color(0xFF9E8C90) val md_theme_dark_inverseOnSurface = Color(0xFF001F2A) val md_theme_dark_inverseSurface = Color(0xFFBFE9FF) val md_theme_dark_inversePrimary = Color(0xFF984061) val md_theme_dark_surfaceTint = Color(0xFFFFB0C8) val md_theme_dark_outlineVariant = Color(0xFF514347) val md_theme_dark_scrim = Color(0xFF000000)
AndroidLearning/compose-training-tip-calculator/app/src/main/java/com/example/tiptime/ui/theme/Color.kt
3409203932
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.tiptime.ui.theme import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext private val LightColorScheme = lightColorScheme( primary = md_theme_light_primary, onPrimary = md_theme_light_onPrimary, primaryContainer = md_theme_light_primaryContainer, onPrimaryContainer = md_theme_light_onPrimaryContainer, secondary = md_theme_light_secondary, onSecondary = md_theme_light_onSecondary, secondaryContainer = md_theme_light_secondaryContainer, onSecondaryContainer = md_theme_light_onSecondaryContainer, tertiary = md_theme_light_tertiary, onTertiary = md_theme_light_onTertiary, tertiaryContainer = md_theme_light_tertiaryContainer, onTertiaryContainer = md_theme_light_onTertiaryContainer, error = md_theme_light_error, errorContainer = md_theme_light_errorContainer, onError = md_theme_light_onError, onErrorContainer = md_theme_light_onErrorContainer, background = md_theme_light_background, onBackground = md_theme_light_onBackground, surface = md_theme_light_surface, onSurface = md_theme_light_onSurface, surfaceVariant = md_theme_light_surfaceVariant, onSurfaceVariant = md_theme_light_onSurfaceVariant, outline = md_theme_light_outline, inverseOnSurface = md_theme_light_inverseOnSurface, inverseSurface = md_theme_light_inverseSurface, inversePrimary = md_theme_light_inversePrimary, surfaceTint = md_theme_light_surfaceTint, outlineVariant = md_theme_light_outlineVariant, scrim = md_theme_light_scrim, ) private val DarkColorScheme = darkColorScheme( primary = md_theme_dark_primary, onPrimary = md_theme_dark_onPrimary, primaryContainer = md_theme_dark_primaryContainer, onPrimaryContainer = md_theme_dark_onPrimaryContainer, secondary = md_theme_dark_secondary, onSecondary = md_theme_dark_onSecondary, secondaryContainer = md_theme_dark_secondaryContainer, onSecondaryContainer = md_theme_dark_onSecondaryContainer, tertiary = md_theme_dark_tertiary, onTertiary = md_theme_dark_onTertiary, tertiaryContainer = md_theme_dark_tertiaryContainer, onTertiaryContainer = md_theme_dark_onTertiaryContainer, error = md_theme_dark_error, errorContainer = md_theme_dark_errorContainer, onError = md_theme_dark_onError, onErrorContainer = md_theme_dark_onErrorContainer, background = md_theme_dark_background, onBackground = md_theme_dark_onBackground, surface = md_theme_dark_surface, onSurface = md_theme_dark_onSurface, surfaceVariant = md_theme_dark_surfaceVariant, onSurfaceVariant = md_theme_dark_onSurfaceVariant, outline = md_theme_dark_outline, inverseOnSurface = md_theme_dark_inverseOnSurface, inverseSurface = md_theme_dark_inverseSurface, inversePrimary = md_theme_dark_inversePrimary, surfaceTint = md_theme_dark_surfaceTint, outlineVariant = md_theme_dark_outlineVariant, scrim = md_theme_dark_scrim, ) @Composable fun TipTimeTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ // Dynamic color in this app is turned off for learning purposes dynamicColor: Boolean = false, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
AndroidLearning/compose-training-tip-calculator/app/src/main/java/com/example/tiptime/ui/theme/Theme.kt
3312208453
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.tiptime.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( displaySmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Bold, fontSize = 36.sp, lineHeight = 44.sp, letterSpacing = 0.sp, ) )
AndroidLearning/compose-training-tip-calculator/app/src/main/java/com/example/tiptime/ui/theme/Type.kt
2149473445
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.tiptime import android.annotation.SuppressLint import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.annotation.StringRes import androidx.annotation.VisibleForTesting import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawingPadding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.tiptime.ui.theme.TipTimeTheme import java.text.NumberFormat class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { enableEdgeToEdge() super.onCreate(savedInstanceState) setContent { TipTimeTheme { Surface( modifier = Modifier.fillMaxSize(), ) { TipTimeLayout() } } } } } @Composable fun TipTimeLayout() { var roundUp by remember { mutableStateOf(false) } var tipInput by remember { mutableStateOf("") } var amountInput by remember { mutableStateOf("") } val tipPercent = tipInput.toDoubleOrNull() ?: 0.0 val amount = amountInput.toDoubleOrNull() ?: 0.0 val tip = calculateTip(amount, tipPercent,roundUp) Column( modifier = Modifier .statusBarsPadding() .padding(horizontal = 40.dp) .safeDrawingPadding() .verticalScroll(rememberScrollState()), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text( text = stringResource(R.string.calculate_tip), modifier = Modifier .padding(bottom = 16.dp, top = 40.dp) .align(alignment = Alignment.Start) ) EditNumberField( lable = R.string.bill_amount, amountInput, { amountInput = it }, keyboardOptions = KeyboardOptions.Default.copy( keyboardType = KeyboardType.Number, imeAction = ImeAction.Next ), modifier = Modifier .padding(bottom = 32.dp) .fillMaxWidth() ) EditNumberField( lable = R.string.how_was_the_service, value = tipInput, onValueChange = { tipInput = it }, keyboardOptions = KeyboardOptions.Default.copy( keyboardType = KeyboardType.Number, imeAction = ImeAction.Done ), modifier = Modifier .padding(bottom = 32.dp) .fillMaxWidth() ) RoundupTheTipRow( roundUp = roundUp, onRoundUpChanged = { roundUp = it }, modifier = Modifier.padding(bottom = 32.dp) ) Text( text = stringResource(R.string.tip_amount, tip), style = MaterialTheme.typography.displaySmall ) Spacer(modifier = Modifier.height(150.dp)) } } /** * Calculates the tip based on the user input and format the tip amount * according to the local currency. * Example would be "$10.00". */ @VisibleForTesting internal fun calculateTip(amount: Double, tipPercent: Double = 15.0,roundUp: Boolean): String { var tip = tipPercent / 100 * amount if (roundUp){ tip=kotlin.math.ceil(tip) } return NumberFormat.getCurrencyInstance().format(tip) } @SuppressLint("UnrememberedMutableState") @Composable fun EditNumberField( @StringRes lable: Int, value: String, onValueChange: (String) -> Unit, keyboardOptions: KeyboardOptions, modifier: Modifier = Modifier ) { TextField( modifier = modifier, keyboardOptions = keyboardOptions, singleLine = true, label = { Text(text = stringResource(id = lable)) }, value = value, onValueChange = { onValueChange(it) } ) } @Composable fun RoundupTheTipRow( roundUp: Boolean, onRoundUpChanged: (Boolean) -> Unit, modifier: Modifier = Modifier ) { Row( modifier = modifier .fillMaxWidth() .size(48.dp), verticalAlignment = Alignment.CenterVertically ) { Text(text = stringResource(R.string.round_up_tip)) Switch( checked = roundUp, onCheckedChange = {onRoundUpChanged(it)}, modifier = modifier .fillMaxWidth() .wrapContentWidth(Alignment.End) ) } } @Preview(showBackground = true) @Composable fun TipTimeLayoutPreview() { TipTimeTheme { TipTimeLayout() } }
AndroidLearning/compose-training-tip-calculator/app/src/main/java/com/example/tiptime/MainActivity.kt
1356978102
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.sports.ui import androidx.lifecycle.ViewModel import com.example.sports.data.LocalSportsDataProvider import com.example.sports.model.Sport import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.update /** * View Model for Sports app */ class SportsViewModel : ViewModel() { private val _uiState = MutableStateFlow( SportsUiState( sportsList = LocalSportsDataProvider.getSportsData(), currentSport = LocalSportsDataProvider.getSportsData().getOrElse(0) { LocalSportsDataProvider.defaultSport } ) ) val uiState: StateFlow<SportsUiState> = _uiState fun updateCurrentSport(selectedSport: Sport) { _uiState.update { it.copy(currentSport = selectedSport) } } fun navigateToListPage() { _uiState.update { it.copy(isShowingListPage = true) } } fun navigateToDetailPage() { _uiState.update { it.copy(isShowingListPage = false) } } } data class SportsUiState( val sportsList: List<Sport> = emptyList(), val currentSport: Sport = LocalSportsDataProvider.defaultSport, val isShowingListPage: Boolean = true )
AndroidLearning/compose-training-sports/app/src/main/java/com/example/sports/ui/SportsViewModel.kt
3939633654
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.sports.ui.theme import androidx.compose.ui.graphics.Color val md_theme_light_primary = Color(0xFF346A22) val md_theme_light_onPrimary = Color(0xFFFFFFFF) val md_theme_light_primaryContainer = Color(0xFFB4F399) val md_theme_light_onPrimaryContainer = Color(0xFF042100) val md_theme_light_secondary = Color(0xFF54624D) val md_theme_light_onSecondary = Color(0xFFFFFFFF) val md_theme_light_secondaryContainer = Color(0xFFD8E7CC) val md_theme_light_onSecondaryContainer = Color(0xFF131F0E) val md_theme_light_tertiary = Color(0xFF006492) val md_theme_light_onTertiary = Color(0xFFFFFFFF) val md_theme_light_tertiaryContainer = Color(0xFFC9E6FF) val md_theme_light_onTertiaryContainer = Color(0xFF001E2F) val md_theme_light_error = Color(0xFFBA1A1A) val md_theme_light_errorContainer = Color(0xFFFFDAD6) val md_theme_light_onError = Color(0xFFFFFFFF) val md_theme_light_onErrorContainer = Color(0xFF410002) val md_theme_light_background = Color(0xFFFDFDF6) val md_theme_light_onBackground = Color(0xFF1A1C18) val md_theme_light_surface = Color(0xFFFDFDF6) val md_theme_light_onSurface = Color(0xFFFFFFFF) val md_theme_light_surfaceVariant = Color(0xFFDFE4D7) val md_theme_light_onSurfaceVariant = Color(0xFF43483F) val md_theme_light_outline = Color(0xFF73796E) val md_theme_light_inverseOnSurface = Color(0xFFF1F1EA) val md_theme_light_inverseSurface = Color(0xFF2F312D) val md_theme_light_inversePrimary = Color(0xFF99D680) val md_theme_light_surfaceTint = Color(0xFF346A22) val md_theme_light_outlineVariant = Color(0xFFC3C8BB) val md_theme_light_scrim = Color(0xFF000000) val md_theme_dark_primary = Color(0xFF99D680) val md_theme_dark_onPrimary = Color(0xFF0B3900) val md_theme_dark_primaryContainer = Color(0xFF1C520A) val md_theme_dark_onPrimaryContainer = Color(0xFFB4F399) val md_theme_dark_secondary = Color(0xFFBCCBB0) val md_theme_dark_onSecondary = Color(0xFF273421) val md_theme_dark_secondaryContainer = Color(0xFF3D4B36) val md_theme_dark_onSecondaryContainer = Color(0xFFD8E7CC) val md_theme_dark_tertiary = Color(0xFF8BCEFF) val md_theme_dark_onTertiary = Color(0xFF00344E) val md_theme_dark_tertiaryContainer = Color(0xFF004B6F) val md_theme_dark_onTertiaryContainer = Color(0xFFC9E6FF) val md_theme_dark_error = Color(0xFFFFB4AB) val md_theme_dark_errorContainer = Color(0xFF93000A) val md_theme_dark_onError = Color(0xFF690005) val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6) val md_theme_dark_background = Color(0xFF1A1C18) val md_theme_dark_onBackground = Color(0xFFE3E3DC) val md_theme_dark_surface = Color(0xFF1A1C18) val md_theme_dark_onSurface = Color(0xFF1A1C18) val md_theme_dark_surfaceVariant = Color(0xFF43483F) val md_theme_dark_onSurfaceVariant = Color(0xFFC3C8BB) val md_theme_dark_outline = Color(0xFF8D9387) val md_theme_dark_inverseOnSurface = Color(0xFF1A1C18) val md_theme_dark_inverseSurface = Color(0xFFE3E3DC) val md_theme_dark_inversePrimary = Color(0xFF346A22) val md_theme_dark_surfaceTint = Color(0xFF99D680) val md_theme_dark_outlineVariant = Color(0xFF43483F) val md_theme_dark_scrim = Color(0xFF000000)
AndroidLearning/compose-training-sports/app/src/main/java/com/example/sports/ui/theme/Color.kt
1948174864
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.sports.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val LightColorScheme = lightColorScheme( primary = md_theme_light_primary, onPrimary = md_theme_light_onPrimary, primaryContainer = md_theme_light_primaryContainer, onPrimaryContainer = md_theme_light_onPrimaryContainer, secondary = md_theme_light_secondary, onSecondary = md_theme_light_onSecondary, secondaryContainer = md_theme_light_secondaryContainer, onSecondaryContainer = md_theme_light_onSecondaryContainer, tertiary = md_theme_light_tertiary, onTertiary = md_theme_light_onTertiary, tertiaryContainer = md_theme_light_tertiaryContainer, onTertiaryContainer = md_theme_light_onTertiaryContainer, error = md_theme_light_error, errorContainer = md_theme_light_errorContainer, onError = md_theme_light_onError, onErrorContainer = md_theme_light_onErrorContainer, background = md_theme_light_background, onBackground = md_theme_light_onBackground, surface = md_theme_light_surface, onSurface = md_theme_light_onSurface, surfaceVariant = md_theme_light_surfaceVariant, onSurfaceVariant = md_theme_light_onSurfaceVariant, outline = md_theme_light_outline, inverseOnSurface = md_theme_light_inverseOnSurface, inverseSurface = md_theme_light_inverseSurface, inversePrimary = md_theme_light_inversePrimary, surfaceTint = md_theme_light_surfaceTint, outlineVariant = md_theme_light_outlineVariant, scrim = md_theme_light_scrim, ) private val DarkColorScheme = darkColorScheme( primary = md_theme_dark_primary, onPrimary = md_theme_dark_onPrimary, primaryContainer = md_theme_dark_primaryContainer, onPrimaryContainer = md_theme_dark_onPrimaryContainer, secondary = md_theme_dark_secondary, onSecondary = md_theme_dark_onSecondary, secondaryContainer = md_theme_dark_secondaryContainer, onSecondaryContainer = md_theme_dark_onSecondaryContainer, tertiary = md_theme_dark_tertiary, onTertiary = md_theme_dark_onTertiary, tertiaryContainer = md_theme_dark_tertiaryContainer, onTertiaryContainer = md_theme_dark_onTertiaryContainer, error = md_theme_dark_error, errorContainer = md_theme_dark_errorContainer, onError = md_theme_dark_onError, onErrorContainer = md_theme_dark_onErrorContainer, background = md_theme_dark_background, onBackground = md_theme_dark_onBackground, surface = md_theme_dark_surface, onSurface = md_theme_dark_onSurface, surfaceVariant = md_theme_dark_surfaceVariant, onSurfaceVariant = md_theme_dark_onSurfaceVariant, outline = md_theme_dark_outline, inverseOnSurface = md_theme_dark_inverseOnSurface, inverseSurface = md_theme_dark_inverseSurface, inversePrimary = md_theme_dark_inversePrimary, surfaceTint = md_theme_dark_surfaceTint, outlineVariant = md_theme_dark_outlineVariant, scrim = md_theme_dark_scrim, ) @Composable fun SportsTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = false, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
AndroidLearning/compose-training-sports/app/src/main/java/com/example/sports/ui/theme/Theme.kt
2732925543
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.sports.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) )
AndroidLearning/compose-training-sports/app/src/main/java/com/example/sports/ui/theme/Type.kt
2996951134
/* * Copyright (c) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.sports.ui import androidx.activity.compose.BackHandler import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.calculateEndPadding import androidx.compose.foundation.layout.calculateStartPadding import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import com.example.sports.R import com.example.sports.data.LocalSportsDataProvider import com.example.sports.model.Sport import com.example.sports.ui.theme.SportsTheme import com.example.sports.utils.SportsContentType import com.example.sports.utils.SportsContentType.* /** * Main composable that serves as container * which displays content according to [uiState] and [windowSize] */ @Composable fun SportsApp( windowSize: WindowWidthSizeClass, onBackPressed: () -> Unit, modifier: Modifier = Modifier ) { val viewModel: SportsViewModel = viewModel() val uiState by viewModel.uiState.collectAsState() var contentType: SportsContentType = when (windowSize) { WindowWidthSizeClass.Compact -> { ListOnly } WindowWidthSizeClass.Medium -> { ListOnly } WindowWidthSizeClass.Expanded -> { ListAndDetail } else -> { ListOnly } } Scaffold( topBar = { SportsAppBar( isShowingListPage = uiState.isShowingListPage, onBackButtonClick = { viewModel.navigateToListPage() }, ) } ) { innerPadding -> if (contentType == ListAndDetail) { SportsListAndDetails( sports = uiState.sportsList, selectedSport = uiState.currentSport, onClick = { viewModel.updateCurrentSport(it) }, onBackPressed = onBackPressed, contentPadding = innerPadding, modifier = Modifier.fillMaxWidth() ) } else { if (uiState.isShowingListPage) { SportsList( sports = uiState.sportsList, onClick = { viewModel.updateCurrentSport(it) viewModel.navigateToDetailPage() }, contentPadding = innerPadding, modifier = Modifier .fillMaxWidth() .padding( top = dimensionResource(R.dimen.padding_medium), start = dimensionResource(R.dimen.padding_medium), end = dimensionResource(R.dimen.padding_medium), ) ) } else { SportsDetail( selectedSport = uiState.currentSport, contentPadding = innerPadding, onBackPressed = { viewModel.navigateToListPage() } ) } } } } /** * Composable that displays the topBar and displays back button if back navigation is possible. */ @OptIn(ExperimentalMaterial3Api::class) @Composable fun SportsAppBar( onBackButtonClick: () -> Unit, isShowingListPage: Boolean, modifier: Modifier = Modifier ) { TopAppBar( title = { Text( text = if (!isShowingListPage) { stringResource(R.string.detail_fragment_label) } else { stringResource(R.string.list_fragment_label) } ) }, navigationIcon = if (!isShowingListPage) { { IconButton(onClick = onBackButtonClick) { Icon( imageVector = Icons.Filled.ArrowBack, contentDescription = stringResource(R.string.back_button) ) } } } else { { Box {} } }, colors = TopAppBarDefaults.topAppBarColors( containerColor = MaterialTheme.colorScheme.primary ), modifier = modifier, ) } @OptIn(ExperimentalMaterial3Api::class) @Composable private fun SportsListItem( sport: Sport, onItemClick: (Sport) -> Unit, modifier: Modifier = Modifier ) { Card( elevation = CardDefaults.cardElevation(), modifier = modifier, shape = RoundedCornerShape(dimensionResource(R.dimen.card_corner_radius)), onClick = { onItemClick(sport) } ) { Row( modifier = Modifier .fillMaxWidth() .size(dimensionResource(R.dimen.card_image_height)) ) { SportsListImageItem( sport = sport, modifier = Modifier.size(dimensionResource(R.dimen.card_image_height)) ) Column( modifier = Modifier .padding( vertical = dimensionResource(R.dimen.padding_small), horizontal = dimensionResource(R.dimen.padding_medium) ) .weight(1f) ) { Text( text = stringResource(sport.titleResourceId), style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(bottom = dimensionResource(R.dimen.card_text_vertical_space)) ) Text( text = stringResource(sport.subtitleResourceId), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.secondary, overflow = TextOverflow.Ellipsis, maxLines = 3 ) Spacer(Modifier.weight(1f)) Row { Text( text = pluralStringResource( R.plurals.player_count_caption, sport.playerCount, sport.playerCount ), style = MaterialTheme.typography.bodySmall ) Spacer(Modifier.weight(1f)) if (sport.olympic) { Text( text = stringResource(R.string.olympic_caption), style = MaterialTheme.typography.labelMedium ) } } } } } } @Composable private fun SportsListImageItem(sport: Sport, modifier: Modifier = Modifier) { Box( modifier = modifier ) { Image( painter = painterResource(sport.imageResourceId), contentDescription = null, alignment = Alignment.Center, contentScale = ContentScale.FillWidth ) } } @Composable private fun SportsList( sports: List<Sport>, onClick: (Sport) -> Unit, modifier: Modifier = Modifier, contentPadding: PaddingValues = PaddingValues(0.dp), ) { LazyColumn( contentPadding = contentPadding, verticalArrangement = Arrangement.spacedBy(dimensionResource(R.dimen.padding_medium)), modifier = modifier, ) { items(sports, key = { sport -> sport.id }) { sport -> SportsListItem( sport = sport, onItemClick = onClick ) } } } @Composable private fun SportsDetail( selectedSport: Sport, onBackPressed: () -> Unit, contentPadding: PaddingValues, modifier: Modifier = Modifier ) { BackHandler { onBackPressed() } val scrollState = rememberScrollState() val layoutDirection = LocalLayoutDirection.current Box( modifier = modifier .verticalScroll(state = scrollState) .padding(top = contentPadding.calculateTopPadding()) ) { Column( modifier = Modifier .padding( bottom = contentPadding.calculateTopPadding(), start = contentPadding.calculateStartPadding(layoutDirection), end = contentPadding.calculateEndPadding(layoutDirection) ) ) { Box { Box { Image( painter = painterResource(selectedSport.sportsImageBanner), contentDescription = null, alignment = Alignment.TopCenter, contentScale = ContentScale.FillWidth, ) } Column( Modifier .align(Alignment.BottomStart) .fillMaxWidth() .background( Brush.verticalGradient( listOf(Color.Transparent, MaterialTheme.colorScheme.scrim), 0f, 400f ) ) ) { Text( text = stringResource(selectedSport.titleResourceId), style = MaterialTheme.typography.headlineLarge, color = MaterialTheme.colorScheme.inverseOnSurface, modifier = Modifier .padding(horizontal = dimensionResource(R.dimen.padding_small)) ) Row( modifier = Modifier.padding(dimensionResource(R.dimen.padding_small)) ) { Text( text = pluralStringResource( R.plurals.player_count_caption, selectedSport.playerCount, selectedSport.playerCount ), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.inverseOnSurface, ) Spacer(Modifier.weight(1f)) Text( text = stringResource(R.string.olympic_caption), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.inverseOnSurface, ) } } } Text( text = stringResource(selectedSport.sportDetails), style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding( vertical = dimensionResource(R.dimen.padding_detail_content_vertical), horizontal = dimensionResource(R.dimen.padding_detail_content_horizontal) ) ) } } } @Composable fun SportsListAndDetails( sports: List<Sport>, selectedSport: Sport, onClick: (Sport) -> Unit, onBackPressed: () -> Unit, modifier: Modifier = Modifier, contentPadding: PaddingValues = PaddingValues(0.dp), ) { Row( modifier = modifier ) { SportsList( sports = sports, onClick = onClick, contentPadding = PaddingValues( top = contentPadding.calculateTopPadding(), ), modifier = Modifier .weight(2f) .padding(horizontal = dimensionResource(R.dimen.padding_medium)) ) SportsDetail( selectedSport = selectedSport, modifier = Modifier.weight(3f), contentPadding = PaddingValues( top = contentPadding.calculateTopPadding(), ), onBackPressed = onBackPressed, ) } } @Preview @Composable fun SportsListItemPreview() { SportsTheme { SportsListItem( sport = LocalSportsDataProvider.defaultSport, onItemClick = {} ) } } @Preview @Composable fun SportsListPreview() { SportsTheme { Surface { SportsList( sports = LocalSportsDataProvider.getSportsData(), onClick = {}, ) } } } @Preview(showBackground = true) @Composable fun Details() { SportsDetail( selectedSport = LocalSportsDataProvider.getSportsData().get(0), onBackPressed = { /*TODO*/ }, contentPadding = PaddingValues(10.dp) ) } @Preview(showBackground = true, widthDp = 1000) @Composable fun SportsListAndDetailsPreview() { SportsListAndDetails( sports = LocalSportsDataProvider.getSportsData(), selectedSport = LocalSportsDataProvider.getSportsData().get(1), onClick = { // }, onBackPressed = {}, contentPadding = PaddingValues(10.dp), modifier = Modifier.fillMaxWidth() ) }
AndroidLearning/compose-training-sports/app/src/main/java/com/example/sports/ui/SportsScreens.kt
3481690796
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.sports import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.material3.Surface import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi import androidx.compose.material3.windowsizeclass.calculateWindowSizeClass import com.example.sports.ui.SportsApp import com.example.sports.ui.theme.SportsTheme /** * Activity for Sports app */ class MainActivity : ComponentActivity() { @OptIn(ExperimentalMaterial3WindowSizeClassApi::class) override fun onCreate(savedInstanceState: Bundle?) { enableEdgeToEdge() super.onCreate(savedInstanceState) setContent { SportsTheme { Surface { val windowSize = calculateWindowSizeClass(activity = this@MainActivity) SportsApp( windowSize = windowSize.widthSizeClass, onBackPressed = { finish() } ) } } } } }
AndroidLearning/compose-training-sports/app/src/main/java/com/example/sports/MainActivity.kt
4115886254
/* * Copyright 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.sports.utils /** * Content shown depending on size and state of device. */ enum class SportsContentType { ListOnly, ListAndDetail }
AndroidLearning/compose-training-sports/app/src/main/java/com/example/sports/utils/WindowStateUtils.kt
3200165300
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.sports.model import androidx.annotation.DrawableRes import androidx.annotation.StringRes /** * Data model for Sport */ data class Sport( val id: Int, @StringRes val titleResourceId: Int, @StringRes val subtitleResourceId: Int, val playerCount: Int, val olympic: Boolean, @DrawableRes val imageResourceId: Int, @DrawableRes val sportsImageBanner: Int, @StringRes val sportDetails: Int )
AndroidLearning/compose-training-sports/app/src/main/java/com/example/sports/model/Sport.kt
1329305924
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.sports.data import com.example.sports.R import com.example.sports.model.Sport /** * Sports data */ object LocalSportsDataProvider { val defaultSport = getSportsData()[0] fun getSportsData(): List<Sport> { return listOf( Sport( id = 1, titleResourceId = R.string.baseball, subtitleResourceId = R.string.sports_list_subtitle, playerCount = 9, olympic = true, imageResourceId = R.drawable.ic_baseball_square, sportsImageBanner = R.drawable.ic_baseball_banner, sportDetails = R.string.sport_detail_text ), Sport( id = 2, titleResourceId = R.string.badminton, subtitleResourceId = R.string.sports_list_subtitle, playerCount = 1, olympic = true, imageResourceId = R.drawable.ic_badminton_square, sportsImageBanner = R.drawable.ic_badminton_banner, sportDetails = R.string.sport_detail_text ), Sport( id = 3, titleResourceId = R.string.basketball, subtitleResourceId = R.string.sports_list_subtitle, playerCount = 5, olympic = true, imageResourceId = R.drawable.ic_basketball_square, sportsImageBanner = R.drawable.ic_basketball_banner, sportDetails = R.string.sport_detail_text ), Sport( id = 4, titleResourceId = R.string.bowling, subtitleResourceId = R.string.sports_list_subtitle, playerCount = 1, olympic = false, imageResourceId = R.drawable.ic_bowling_square, sportsImageBanner = R.drawable.ic_bowling_banner, sportDetails = R.string.sport_detail_text ), Sport( id = 5, titleResourceId = R.string.cycling, subtitleResourceId = R.string.sports_list_subtitle, playerCount = 1, olympic = true, imageResourceId = R.drawable.ic_cycling_square, sportsImageBanner = R.drawable.ic_cycling_banner, sportDetails = R.string.sport_detail_text ), Sport( id = 6, titleResourceId = R.string.golf, subtitleResourceId = R.string.sports_list_subtitle, playerCount = 1, olympic = false, imageResourceId = R.drawable.ic_golf_square, sportsImageBanner = R.drawable.ic_golf_banner, sportDetails = R.string.sport_detail_text ), Sport( id = 7, titleResourceId = R.string.running, subtitleResourceId = R.string.sports_list_subtitle, playerCount = 1, olympic = true, imageResourceId = R.drawable.ic_running_square, sportsImageBanner = R.drawable.ic_running_banner, sportDetails = R.string.sport_detail_text ), Sport( id = 8, titleResourceId = R.string.soccer, subtitleResourceId = R.string.sports_list_subtitle, playerCount = 11, olympic = true, imageResourceId = R.drawable.ic_soccer_square, sportsImageBanner = R.drawable.ic_soccer_banner, sportDetails = R.string.sport_detail_text ), Sport( id = 9, titleResourceId = R.string.swimming, subtitleResourceId = R.string.sports_list_subtitle, playerCount = 1, olympic = true, imageResourceId = R.drawable.ic_swimming_square, sportsImageBanner = R.drawable.ic_swimming_banner, sportDetails = R.string.sport_detail_text ), Sport( id = 10, titleResourceId = R.string.table_tennis, subtitleResourceId = R.string.sports_list_subtitle, playerCount = 1, olympic = true, imageResourceId = R.drawable.ic_table_tennis_square, sportsImageBanner = R.drawable.ic_table_tennis_banner, sportDetails = R.string.sport_detail_text ), Sport( id = 11, titleResourceId = R.string.tennis, subtitleResourceId = R.string.sports_list_subtitle, playerCount = 1, olympic = true, imageResourceId = R.drawable.ic_tennis_square, sportsImageBanner = R.drawable.ic_tennis_banner, sportDetails = R.string.sport_detail_text ) ) } }
AndroidLearning/compose-training-sports/app/src/main/java/com/example/sports/data/LocalSportsDataProvider.kt
2306095776
package com.example.dessertclicker.ui import androidx.lifecycle.ViewModel import com.example.dessertclicker.data.Datasource.dessertList import com.example.dessertclicker.data.DessertUiState import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update class DessertViewModel : ViewModel() { private val _dessertUiState = MutableStateFlow<DessertUiState>(DessertUiState()) val dessertUiState = _dessertUiState.asStateFlow() fun onDessertClicked() { _dessertUiState.update { val dessertsSold = it.dessertsSold + 1 val nextDessertIndex = determineDessertIndex(dessertsSold) it.copy( currentDessertIndex = nextDessertIndex, revenue = it.revenue + it.currentDessertPrice, currentDessertImageId = dessertList[nextDessertIndex].imageId, currentDessertPrice = dessertList[nextDessertIndex].price ) } } private fun determineDessertIndex(dessertsSold: Int): Int { var dessertIndex = 0 for (index in dessertList.indices) { if (dessertsSold >= dessertList[index].startProductionAmount) { dessertIndex = index } else { // The list of desserts is sorted by startProductionAmount. As you sell more // desserts, you'll start producing more expensive desserts as determined by // startProductionAmount. We know to break as soon as we see a dessert who's // "startProductionAmount" is greater than the amount sold. break } } return dessertIndex } }
AndroidLearning/compose-training-dessert-clicker/app/src/main/java/com/example/dessertclicker/ui/DessertViewModel.kt
440035031
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.dessertclicker.ui.theme import androidx.compose.ui.graphics.Color val md_theme_light_primary = Color(0xFF006781) val md_theme_light_onPrimary = Color(0xFFFFFFFF) val md_theme_light_secondaryContainer = Color(0xFFCFE6F1) val md_theme_light_onSecondaryContainer = Color(0xFF071E26) val md_theme_light_background = Color(0xFFFBFCFE) val md_theme_dark_primary = Color(0xFF5FD4FD) val md_theme_dark_onPrimary = Color(0xFF003544) val md_theme_dark_secondaryContainer = Color(0xFF354A53) val md_theme_dark_onSecondaryContainer = Color(0xFFCFE6F1) val md_theme_dark_background = Color(0xFF191C1D)
AndroidLearning/compose-training-dessert-clicker/app/src/main/java/com/example/dessertclicker/ui/theme/Color.kt
3898211958
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.dessertclicker.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = md_theme_dark_primary, onPrimary = md_theme_dark_onPrimary, secondaryContainer = md_theme_dark_secondaryContainer, onSecondaryContainer = md_theme_dark_onSecondaryContainer, background = md_theme_dark_background, ) private val LightColorScheme = lightColorScheme( primary = md_theme_light_primary, onPrimary = md_theme_light_onPrimary, secondaryContainer = md_theme_light_secondaryContainer, onSecondaryContainer = md_theme_light_onSecondaryContainer, background = md_theme_light_background, ) @Composable fun DessertClickerTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ // Dynamic color in this app is turned off for learning purposes dynamicColor: Boolean = false, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() window.navigationBarColor = colorScheme.secondaryContainer.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, content = content ) }
AndroidLearning/compose-training-dessert-clicker/app/src/main/java/com/example/dessertclicker/ui/theme/Theme.kt
3237981663
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.dessertclicker import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.annotation.DrawableRes import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.asPaddingValues import androidx.compose.foundation.layout.calculateEndPadding import androidx.compose.foundation.layout.calculateStartPadding import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawing import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.foundation.layout.width import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Share import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.core.content.ContextCompat import com.example.dessertclicker.data.Datasource import com.example.dessertclicker.model.Dessert import com.example.dessertclicker.ui.DessertViewModel import com.example.dessertclicker.ui.theme.DessertClickerTheme class MainActivity : ComponentActivity() { companion object { private const val TAG = "MainActivity" } override fun onCreate(savedInstanceState: Bundle?) { enableEdgeToEdge() super.onCreate(savedInstanceState) Log.d(TAG, "onCreate Called") setContent { DessertClickerTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier .fillMaxSize() .statusBarsPadding(), ) { DessertClickerApp(desserts = Datasource.dessertList) } } } } override fun onStart() { super.onStart() Log.d(TAG, "onStart Called") } override fun onResume() { super.onResume() Log.d(TAG, "onResume Called") } override fun onRestart() { super.onRestart() Log.d(TAG, "onRestart Called") } override fun onPause() { super.onPause() Log.d(TAG, "onPause Called") } override fun onStop() { super.onStop() Log.d(TAG, "onStop Called") } override fun onDestroy() { super.onDestroy() Log.d(TAG, "onDestroy Called") } } /** * Share desserts sold information using ACTION_SEND intent */ private fun shareSoldDessertsInformation(intentContext: Context, dessertsSold: Int, revenue: Int) { val sendIntent = Intent().apply { action = Intent.ACTION_SEND putExtra( Intent.EXTRA_TEXT, intentContext.getString(R.string.share_text, dessertsSold, revenue) ) type = "text/plain" } val shareIntent = Intent.createChooser(sendIntent, null) try { ContextCompat.startActivity(intentContext, shareIntent, null) } catch (e: ActivityNotFoundException) { Toast.makeText( intentContext, intentContext.getString(R.string.sharing_not_available), Toast.LENGTH_LONG ).show() } } @Composable private fun DessertClickerApp( desserts: List<Dessert>, viewModel: DessertViewModel = DessertViewModel() ) { val uiState by viewModel.dessertUiState.collectAsState() Scaffold(topBar = { val intentContext = LocalContext.current val layoutDirection = LocalLayoutDirection.current DessertClickerAppBar( onShareButtonClicked = { shareSoldDessertsInformation( intentContext = intentContext, dessertsSold = uiState.dessertsSold, revenue = uiState.revenue ) }, modifier = Modifier .fillMaxWidth() .padding( start = WindowInsets.safeDrawing .asPaddingValues() .calculateStartPadding(layoutDirection), end = WindowInsets.safeDrawing .asPaddingValues() .calculateEndPadding(layoutDirection), ) .background(MaterialTheme.colorScheme.primary) ) }) { contentPadding -> DessertClickerScreen( revenue = uiState.revenue, dessertsSold = uiState.dessertsSold, dessertImageId = uiState.currentDessertImageId, onDessertClicked = { viewModel::onDessertClicked.invoke() }, modifier = Modifier.padding(contentPadding) ) } } @Composable private fun DessertClickerAppBar( onShareButtonClicked: () -> Unit, modifier: Modifier = Modifier ) { Row( modifier = modifier, horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, ) { Text( text = stringResource(R.string.app_name), modifier = Modifier.padding(start = dimensionResource(R.dimen.padding_medium)), color = MaterialTheme.colorScheme.onPrimary, style = MaterialTheme.typography.titleLarge, ) IconButton( onClick = onShareButtonClicked, modifier = Modifier.padding(end = dimensionResource(R.dimen.padding_medium)), ) { Icon( imageVector = Icons.Filled.Share, contentDescription = stringResource(R.string.share), tint = MaterialTheme.colorScheme.onPrimary ) } } } @Composable fun DessertClickerScreen( revenue: Int, dessertsSold: Int, @DrawableRes dessertImageId: Int, onDessertClicked: () -> Unit, modifier: Modifier = Modifier ) { Box(modifier = modifier) { Image( painter = painterResource(R.drawable.bakery_back), contentDescription = null, contentScale = ContentScale.Crop ) Column { Box( modifier = Modifier .weight(1f) .fillMaxWidth(), ) { Image( painter = painterResource(dessertImageId), contentDescription = null, modifier = Modifier .width(dimensionResource(R.dimen.image_size)) .height(dimensionResource(R.dimen.image_size)) .align(Alignment.Center) .clickable { onDessertClicked() }, contentScale = ContentScale.Crop, ) } TransactionInfo( revenue = revenue, dessertsSold = dessertsSold, modifier = Modifier.background(MaterialTheme.colorScheme.secondaryContainer) ) } } } @Composable private fun TransactionInfo( revenue: Int, dessertsSold: Int, modifier: Modifier = Modifier ) { Column(modifier = modifier) { DessertsSoldInfo( dessertsSold = dessertsSold, modifier = Modifier .fillMaxWidth() .padding(dimensionResource(R.dimen.padding_medium)) ) RevenueInfo( revenue = revenue, modifier = Modifier .fillMaxWidth() .padding(dimensionResource(R.dimen.padding_medium)) ) } } @Composable private fun RevenueInfo(revenue: Int, modifier: Modifier = Modifier) { Row( modifier = modifier, horizontalArrangement = Arrangement.SpaceBetween, ) { Text( text = stringResource(R.string.total_revenue), style = MaterialTheme.typography.headlineMedium, color = MaterialTheme.colorScheme.onSecondaryContainer ) Text( text = "$${revenue}", textAlign = TextAlign.Right, style = MaterialTheme.typography.headlineMedium, color = MaterialTheme.colorScheme.onSecondaryContainer ) } } @Composable private fun DessertsSoldInfo(dessertsSold: Int, modifier: Modifier = Modifier) { Row( modifier = modifier, horizontalArrangement = Arrangement.SpaceBetween, ) { Text( text = stringResource(R.string.dessert_sold), style = MaterialTheme.typography.titleLarge, color = MaterialTheme.colorScheme.onSecondaryContainer ) Text( text = dessertsSold.toString(), style = MaterialTheme.typography.titleLarge, color = MaterialTheme.colorScheme.onSecondaryContainer ) } } @Preview @Composable fun MyDessertClickerAppPreview() { DessertClickerTheme { DessertClickerApp(listOf(Dessert(R.drawable.cupcake, 5, 0))) } }
AndroidLearning/compose-training-dessert-clicker/app/src/main/java/com/example/dessertclicker/MainActivity.kt
1459502198
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.dessertclicker.model /** * [Dessert] is the data class to represent the Dessert imageId, price, and startProductionAmount */ data class Dessert( val imageId: Int, val price: Int, val startProductionAmount: Int )
AndroidLearning/compose-training-dessert-clicker/app/src/main/java/com/example/dessertclicker/model/Dessert.kt
260936162
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.dessertclicker.data import com.example.dessertclicker.R import com.example.dessertclicker.model.Dessert /** * [Datasource] generates a list of [Dessert] */ object Datasource { val dessertList = listOf( Dessert(R.drawable.cupcake, 5, 0), Dessert(R.drawable.donut, 10, 5), Dessert(R.drawable.eclair, 15, 20), Dessert(R.drawable.froyo, 30, 50), Dessert(R.drawable.gingerbread, 50, 100), Dessert(R.drawable.honeycomb, 100, 200), Dessert(R.drawable.icecreamsandwich, 500, 500), Dessert(R.drawable.jellybean, 1000, 1000), Dessert(R.drawable.kitkat, 2000, 2000), Dessert(R.drawable.lollipop, 3000, 4000), Dessert(R.drawable.marshmallow, 4000, 8000), Dessert(R.drawable.nougat, 5000, 16000), Dessert(R.drawable.oreo, 6000, 20000) ) }
AndroidLearning/compose-training-dessert-clicker/app/src/main/java/com/example/dessertclicker/data/Datasource.kt
841859431
package com.example.dessertclicker.data import androidx.annotation.DrawableRes import com.example.dessertclicker.data.Datasource.dessertList data class DessertUiState( val currentDessertIndex: Int = 0, val dessertsSold: Int = 0, val revenue: Int = 0, val currentDessertPrice: Int = dessertList[currentDessertIndex].price, @DrawableRes val currentDessertImageId: Int = dessertList[currentDessertIndex].imageId )
AndroidLearning/compose-training-dessert-clicker/app/src/main/java/com/example/dessertclicker/data/DessertUiState.kt
298218059
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.affirmations.ui.theme import androidx.compose.ui.graphics.Color val md_theme_light_background = Color(0xFFFBFCFE) val md_theme_light_surfaceVariant = Color(0xFFE7E0EC) val md_theme_light_onSurfaceVariant = Color(0xFF49454f) val md_theme_dark_background = Color(0xFF191C1D) val md_theme_dark_surfaceVariant = Color(0xFF49454f) val md_theme_dark_onSurfaceVariant = Color(0xFFCAC4D0)
AndroidLearning/compose-training-affirmations/app/src/main/java/com/example/affirmations/ui/theme/Color.kt
306670280
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.affirmations.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( surfaceVariant = md_theme_dark_surfaceVariant, onSurfaceVariant = md_theme_dark_onSurfaceVariant, background = md_theme_dark_background ) private val LightColorScheme = lightColorScheme( surfaceVariant = md_theme_light_surfaceVariant, onSurfaceVariant = md_theme_light_onSurfaceVariant, background = md_theme_light_background ) @Composable fun AffirmationsTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+, turned off for training purposes dynamicColor: Boolean = false, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.background.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = !darkTheme } } MaterialTheme( colorScheme = colorScheme, content = content ) }
AndroidLearning/compose-training-affirmations/app/src/main/java/com/example/affirmations/ui/theme/Theme.kt
4278705566
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.affirmations import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.Card import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.affirmations.data.Datasource import com.example.affirmations.model.Affirmation import com.example.affirmations.ui.theme.AffirmationsTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { AffirmationsTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { AffirmationsApp() } } } } } @Preview @Composable fun AffirmationsApp() { AffirmationList( affirmationList = Datasource().loadAffirmations() ) } @Composable fun AffirmationCard( affirmation: Affirmation, modifier: Modifier = Modifier ) { Card(modifier = modifier) { Column { Image( painter = painterResource(id = affirmation.imageResourceId), contentDescription = stringResource(id = affirmation.stringResourceId), modifier = Modifier .fillMaxWidth() .height(194.dp), contentScale = ContentScale.Crop ) Text( text = stringResource(affirmation.stringResourceId), modifier = Modifier.padding(16.dp), style = MaterialTheme.typography.headlineSmall ) } } } @Composable fun AffirmationList(affirmationList: List<Affirmation>, modifier: Modifier = Modifier) { LazyColumn(modifier = modifier) { items(affirmationList) { AffirmationCard(affirmation = it, modifier = Modifier.padding(8.dp)) } } }
AndroidLearning/compose-training-affirmations/app/src/main/java/com/example/affirmations/MainActivity.kt
2608752274
package com.example.affirmations.model import androidx.annotation.DrawableRes import androidx.annotation.StringRes data class Affirmation( @StringRes val stringResourceId:Int, @DrawableRes val imageResourceId:Int )
AndroidLearning/compose-training-affirmations/app/src/main/java/com/example/affirmations/model/Affirmation.kt
3956691913
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.affirmations.data import com.example.affirmations.R import com.example.affirmations.model.Affirmation //import com.example.affirmations.R //import com.example.affirmations.model.Affirmation /** * [Datasource] generates a list of [Affirmation] */ class Datasource() { fun loadAffirmations(): List<Affirmation> { return listOf<Affirmation>( Affirmation(R.string.affirmation1, R.drawable.image1), Affirmation(R.string.affirmation2, R.drawable.image2), Affirmation(R.string.affirmation3, R.drawable.image3), Affirmation(R.string.affirmation4, R.drawable.image4), Affirmation(R.string.affirmation5, R.drawable.image5), Affirmation(R.string.affirmation6, R.drawable.image6), Affirmation(R.string.affirmation7, R.drawable.image7), Affirmation(R.string.affirmation8, R.drawable.image8), Affirmation(R.string.affirmation9, R.drawable.image9), Affirmation(R.string.affirmation10, R.drawable.image10)) } }
AndroidLearning/compose-training-affirmations/app/src/main/java/com/example/affirmations/data/Datasource.kt
2201905252
package com.example.amphibians import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.amphibians", appContext.packageName) } }
AndroidLearning/Amphibians/app/src/androidTest/java/com/example/amphibians/ExampleInstrumentedTest.kt
1395659388
package com.example.amphibians import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
AndroidLearning/Amphibians/app/src/test/java/com/example/amphibians/ExampleUnitTest.kt
2527638740
@file:OptIn(ExperimentalMaterial3Api::class) package com.example.amphibians.ui import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.TopAppBarScrollBehavior import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.res.stringResource import androidx.lifecycle.viewmodel.compose.viewModel import com.example.amphibians.R import com.example.amphibians.ui.screens.AmphibiansViewModel import com.example.amphibians.ui.screens.HomeScreen @Composable fun AmphibiansApp( modifier: Modifier = Modifier ) { val scrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior() Scaffold( modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection), topBar = { AmphibiansTopAppBar(scrollBehavior = scrollBehavior) } ) { Surface( modifier = Modifier.fillMaxSize() ) { val amphibiansViewModel: AmphibiansViewModel = viewModel(factory = AmphibiansViewModel.Factory) HomeScreen( amphibiansUiState = amphibiansViewModel.amphibiansUiState, retryAction = amphibiansViewModel::getAmphibiansPhotos, it ) } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun AmphibiansTopAppBar(scrollBehavior: TopAppBarScrollBehavior, modifier: Modifier = Modifier) { TopAppBar( scrollBehavior = scrollBehavior, title = { Text(text = stringResource(R.string.amphibians)) }, modifier = modifier ) }
AndroidLearning/Amphibians/app/src/main/java/com/example/amphibians/ui/AmphibiansApp.kt
3578102173
package com.example.amphibians.ui.screens import android.annotation.SuppressLint import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import coil.request.ImageRequest import com.example.amphibians.R import com.example.amphibians.network.AmphibianPhoto @Composable fun HomeScreen( amphibiansUiState: AmphibiansUiState, retryAction: () -> Unit, paddingValues: PaddingValues = PaddingValues(0.dp), @SuppressLint("ModifierParameter") modifier: Modifier = Modifier ) { when (amphibiansUiState) { is AmphibiansUiState.Loading -> LoadingScreen(Modifier.fillMaxSize()) is AmphibiansUiState.Success -> AmphibiansLazyList( amphibians = amphibiansUiState.photos, modifier .fillMaxSize() .padding(paddingValues) ) is AmphibiansUiState.Error -> ErrorScreen(retryAction, Modifier.fillMaxSize()) } } @Composable fun LoadingScreen(modifier: Modifier = Modifier) { Column( modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text(text = "Loading..") CircularProgressIndicator() } } @Composable fun ErrorScreen(retryAction: () -> Unit, modifier: Modifier = Modifier) { Column( modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text(text = "Unable to Load Data") Image(painter = painterResource(id = R.drawable.ic_broken_image), contentDescription = null) Button(onClick = retryAction) { Text(text = "Retry") } } } @Composable fun AmphibiansLazyList(amphibians: List<AmphibianPhoto>, modifier: Modifier = Modifier) { LazyColumn(modifier = modifier) { items(amphibians, key = { amphibian -> amphibian.name }) { amphibian -> AmphibianPhotoCard(ampPhoto = amphibian, Modifier.padding(8.dp)) } } } @Composable fun AmphibianPhotoCard(ampPhoto: AmphibianPhoto, modifier: Modifier = Modifier) { Card(modifier) { Text( text = "${ampPhoto.name} (${ampPhoto.type})", style = MaterialTheme.typography.titleLarge, modifier = Modifier.padding(8.dp) ) AsyncImage( model = ImageRequest.Builder(context = LocalContext.current) .data(ampPhoto.imgSrc) .crossfade(true) .build(), contentScale = ContentScale.Crop, error = painterResource(R.drawable.ic_broken_image), placeholder = painterResource(R.drawable.loading_img), contentDescription = null, modifier = Modifier.fillMaxWidth() ) Text( text = ampPhoto.description, style = MaterialTheme.typography.bodyLarge, modifier = Modifier .fillMaxWidth() .padding(8.dp) ) } } @Preview(showSystemUi = true, showBackground = true) @Composable fun AmpCard() { AmphibianPhotoCard( ampPhoto = AmphibianPhoto( name = "TODOOOODODOD", type = "Hello", imgSrc = "", description = "This is log dsndgk dgh jj d sdiohf f ddofhdh sdfog gsdg ", ), modifier = Modifier.fillMaxSize() ) } @Preview(showSystemUi = true, showBackground = true) @Composable private fun ErrorScreenPreview() { ErrorScreen({}, Modifier.fillMaxSize()) } @Preview(showSystemUi = true, showBackground = true) @Composable fun LoadingScreenPreview() { LoadingScreen(modifier = Modifier.fillMaxSize()) }
AndroidLearning/Amphibians/app/src/main/java/com/example/amphibians/ui/screens/HomeScreen.kt
3670253677
package com.example.amphibians.ui.screens import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory import com.example.amphibians.App import com.example.amphibians.data.AmphibiansDataRepository import com.example.amphibians.network.AmphibianPhoto import kotlinx.coroutines.launch import java.io.IOException sealed interface AmphibiansUiState { data class Success(val photos: List<AmphibianPhoto>) : AmphibiansUiState object Error : AmphibiansUiState object Loading : AmphibiansUiState } class AmphibiansViewModel( private val amphibiansDataRepository: AmphibiansDataRepository ) : ViewModel() { var amphibiansUiState: AmphibiansUiState by mutableStateOf(AmphibiansUiState.Loading) private set init { getAmphibiansPhotos() } fun getAmphibiansPhotos() { viewModelScope.launch { amphibiansUiState = try { AmphibiansUiState.Success(amphibiansDataRepository.getAmphibianData()) } catch (e: IOException) { AmphibiansUiState.Error } } } companion object { val Factory: ViewModelProvider.Factory = viewModelFactory { initializer { val application = (this[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY] as App) val amphibiansDataRepository = application.container.amphibiansDataRepository AmphibiansViewModel(amphibiansDataRepository = amphibiansDataRepository) } } } }
AndroidLearning/Amphibians/app/src/main/java/com/example/amphibians/ui/screens/AmphibiansViewModel.kt
1363501137
package com.example.amphibians.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
AndroidLearning/Amphibians/app/src/main/java/com/example/amphibians/ui/theme/Color.kt
2271846463
package com.example.amphibians.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun AmphibiansTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
AndroidLearning/Amphibians/app/src/main/java/com/example/amphibians/ui/theme/Theme.kt
2562056878
package com.example.amphibians.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
AndroidLearning/Amphibians/app/src/main/java/com/example/amphibians/ui/theme/Type.kt
1584967977
package com.example.amphibians import android.app.Application import com.example.amphibians.data.AppContainer import com.example.amphibians.data.DefaultAppContainer class App : Application() { lateinit var container: AppContainer override fun onCreate() { super.onCreate() container = DefaultAppContainer() } }
AndroidLearning/Amphibians/app/src/main/java/com/example/amphibians/App.kt
2361729860
package com.example.amphibians import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.example.amphibians.ui.AmphibiansApp import com.example.amphibians.ui.theme.AmphibiansTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { enableEdgeToEdge() AmphibiansTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { AmphibiansApp() } } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "Hello $name!", modifier = modifier ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { AmphibiansTheme { Greeting("Android") } }
AndroidLearning/Amphibians/app/src/main/java/com/example/amphibians/MainActivity.kt
3658878883
package com.example.amphibians.network import retrofit2.http.GET interface AmphibiansApiService { @GET("amphibians") suspend fun getData():List<AmphibianPhoto> }
AndroidLearning/Amphibians/app/src/main/java/com/example/amphibians/network/AmphibiansApiService.kt
1782404853
package com.example.amphibians.network import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class AmphibianPhoto( @SerialName(value = "name") val name: String, @SerialName(value = "type") val type: String, @SerialName(value = "description") val description: String, @SerialName(value = "img_src") val imgSrc: String )
AndroidLearning/Amphibians/app/src/main/java/com/example/amphibians/network/AmphibianPhoto.kt
3656920497
package com.example.amphibians.data import com.example.amphibians.network.AmphibiansApiService import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory import kotlinx.serialization.json.Json import okhttp3.MediaType.Companion.toMediaType import retrofit2.Retrofit interface AppContainer { val amphibiansDataRepository: AmphibiansDataRepository } class DefaultAppContainer : AppContainer { private val baseUrl = "https://android-kotlin-fun-mars-server.appspot.com" private val retrofit: Retrofit = Retrofit.Builder() .addConverterFactory(Json.asConverterFactory("application/json".toMediaType())) .baseUrl(baseUrl) .build() private val retrfitService: AmphibiansApiService by lazy { retrofit.create(AmphibiansApiService::class.java) } override val amphibiansDataRepository: AmphibiansDataRepository by lazy { NetworkAmphibianDataReposiory(retrfitService) } }
AndroidLearning/Amphibians/app/src/main/java/com/example/amphibians/data/AppContainer.kt
59383402
package com.example.amphibians.data import com.example.amphibians.network.AmphibianPhoto import com.example.amphibians.network.AmphibiansApiService interface AmphibiansDataRepository { suspend fun getAmphibianData(): List<AmphibianPhoto> } class NetworkAmphibianDataReposiory( private val amphibiansApiService: AmphibiansApiService ) : AmphibiansDataRepository { override suspend fun getAmphibianData() = amphibiansApiService.getData() }
AndroidLearning/Amphibians/app/src/main/java/com/example/amphibians/data/AmphibiansDataRepository.kt
3082947266
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lunchtray.ui import androidx.lifecycle.ViewModel import com.example.lunchtray.model.MenuItem import com.example.lunchtray.model.MenuItem.AccompanimentItem import com.example.lunchtray.model.MenuItem.EntreeItem import com.example.lunchtray.model.MenuItem.SideDishItem import com.example.lunchtray.model.OrderUiState import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import java.text.NumberFormat class OrderViewModel : ViewModel() { private val taxRate = 0.08 private val _uiState = MutableStateFlow(OrderUiState()) val uiState: StateFlow<OrderUiState> = _uiState.asStateFlow() fun updateEntree(entree: EntreeItem) { val previousEntree = _uiState.value.entree updateItem(entree, previousEntree) } fun updateSideDish(sideDish: SideDishItem) { val previousSideDish = _uiState.value.sideDish updateItem(sideDish, previousSideDish) } fun updateAccompaniment(accompaniment: AccompanimentItem) { val previousAccompaniment = _uiState.value.accompaniment updateItem(accompaniment, previousAccompaniment) } fun resetOrder() { _uiState.value = OrderUiState() } private fun updateItem(newItem: MenuItem, previousItem: MenuItem?) { _uiState.update { currentState -> val previousItemPrice = previousItem?.price ?: 0.0 // subtract previous item price in case an item of this category was already added. val itemTotalPrice = currentState.itemTotalPrice - previousItemPrice + newItem.price // recalculate tax val tax = itemTotalPrice * taxRate currentState.copy( itemTotalPrice = itemTotalPrice, orderTax = tax, orderTotalPrice = itemTotalPrice + tax, entree = if (newItem is EntreeItem) newItem else currentState.entree, sideDish = if (newItem is SideDishItem) newItem else currentState.sideDish, accompaniment = if (newItem is AccompanimentItem) newItem else currentState.accompaniment ) } } } fun Double.formatPrice(): String { return NumberFormat.getCurrencyInstance().format(this) }
AndroidLearning/compose-training-lunch-tray/app/src/main/java/com/example/lunchtray/ui/OrderViewModel.kt
275906814
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lunchtray.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.selection.selectable import androidx.compose.material3.Button import androidx.compose.material3.Divider import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.RadioButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import com.example.lunchtray.R import com.example.lunchtray.model.MenuItem @Composable fun BaseMenuScreen( options: List<MenuItem>, modifier: Modifier = Modifier, onCancelButtonClicked: () -> Unit = {}, onNextButtonClicked: () -> Unit = {}, onSelectionChanged: (MenuItem) -> Unit, ) { var selectedItemName by rememberSaveable { mutableStateOf("") } Column(modifier = modifier) { options.forEach { item -> val onClick = { selectedItemName = item.name onSelectionChanged(item) } MenuItemRow( item = item, selectedItemName = selectedItemName, onClick = onClick, modifier = Modifier.selectable( selected = selectedItemName == item.name, onClick = onClick ) ) } MenuScreenButtonGroup( selectedItemName = selectedItemName, onCancelButtonClicked = onCancelButtonClicked, onNextButtonClicked = { // Assert not null bc next button is not enabled unless selectedItem is not null. onNextButtonClicked() }, modifier = Modifier.fillMaxWidth().padding(dimensionResource(R.dimen.padding_medium)) ) } } @Composable fun MenuItemRow( item: MenuItem, selectedItemName: String, onClick: () -> Unit, modifier: Modifier = Modifier ) { Row( modifier = modifier, verticalAlignment = Alignment.CenterVertically ) { RadioButton( selected = selectedItemName == item.name, onClick = onClick ) Column( verticalArrangement = Arrangement.spacedBy(dimensionResource(R.dimen.padding_small)) ) { Text( text = item.name, style = MaterialTheme.typography.headlineSmall ) Text( text = item.description, style = MaterialTheme.typography.bodyLarge ) Text( text = item.getFormattedPrice(), style = MaterialTheme.typography.bodyMedium ) Divider( thickness = dimensionResource(R.dimen.thickness_divider), modifier = Modifier.padding(bottom = dimensionResource(R.dimen.padding_medium)) ) } } } @Composable fun MenuScreenButtonGroup( selectedItemName: String, onCancelButtonClicked: () -> Unit, onNextButtonClicked: () -> Unit, modifier: Modifier = Modifier ) { Row( modifier = modifier, horizontalArrangement = Arrangement.spacedBy(dimensionResource(R.dimen.padding_medium)) ){ OutlinedButton(modifier = Modifier.weight(1f), onClick = onCancelButtonClicked) { Text(stringResource(R.string.cancel).uppercase()) } Button( modifier = Modifier.weight(1f), // the button is enabled when the user makes a selection enabled = selectedItemName.isNotEmpty(), onClick = onNextButtonClicked ) { Text(stringResource(R.string.next).uppercase()) } } }
AndroidLearning/compose-training-lunch-tray/app/src/main/java/com/example/lunchtray/ui/BaseMenuScreen.kt
3087445694
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lunchtray.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.widthIn import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.lunchtray.R @Composable fun StartOrderScreen( onStartOrderButtonClicked: () -> Unit, modifier: Modifier = Modifier ) { Column( modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Button( onClick = onStartOrderButtonClicked, Modifier.widthIn(min = 250.dp) ) { Text(stringResource(R.string.start_order)) } } } @Preview @Composable fun StartOrderPreview(){ StartOrderScreen( onStartOrderButtonClicked = {}, modifier = Modifier .padding(dimensionResource(R.dimen.padding_medium)) .fillMaxSize() ) }
AndroidLearning/compose-training-lunch-tray/app/src/main/java/com/example/lunchtray/ui/StartOrderScreen.kt
3902028927
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lunchtray.ui import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.tooling.preview.Preview import com.example.lunchtray.R import com.example.lunchtray.datasource.DataSource import com.example.lunchtray.model.MenuItem import com.example.lunchtray.model.MenuItem.AccompanimentItem @Composable fun AccompanimentMenuScreen( options: List<AccompanimentItem>, onCancelButtonClicked: () -> Unit, onNextButtonClicked: () -> Unit, onSelectionChanged: (AccompanimentItem) -> Unit, modifier: Modifier = Modifier ) { BaseMenuScreen( options = options, onCancelButtonClicked = onCancelButtonClicked, onNextButtonClicked = onNextButtonClicked, onSelectionChanged = onSelectionChanged as (MenuItem) -> Unit, modifier = modifier ) } @Preview @Composable fun AccompanimentMenuPreview(){ AccompanimentMenuScreen( options = DataSource.accompanimentMenuItems, onNextButtonClicked = {}, onCancelButtonClicked = {}, onSelectionChanged = {}, modifier = Modifier .padding(dimensionResource(R.dimen.padding_medium)) .verticalScroll(rememberScrollState()) ) }
AndroidLearning/compose-training-lunch-tray/app/src/main/java/com/example/lunchtray/ui/AccompanimentMenuScreen.kt
1112164574
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lunchtray.ui import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.tooling.preview.Preview import com.example.lunchtray.R import com.example.lunchtray.datasource.DataSource import com.example.lunchtray.model.MenuItem import com.example.lunchtray.model.MenuItem.EntreeItem @Composable fun EntreeMenuScreen( options: List<EntreeItem>, onCancelButtonClicked: () -> Unit, onNextButtonClicked: () -> Unit, onSelectionChanged: (EntreeItem) -> Unit, modifier: Modifier = Modifier ) { BaseMenuScreen( options = options, onCancelButtonClicked = onCancelButtonClicked, onNextButtonClicked = onNextButtonClicked, onSelectionChanged = onSelectionChanged as (MenuItem) -> Unit, modifier = modifier ) } @Preview @Composable fun EntreeMenuPreview(){ EntreeMenuScreen( options = DataSource.entreeMenuItems, onCancelButtonClicked = {}, onNextButtonClicked = {}, onSelectionChanged = {}, modifier = Modifier .padding(dimensionResource(R.dimen.padding_medium)) .verticalScroll(rememberScrollState()) ) }
AndroidLearning/compose-training-lunch-tray/app/src/main/java/com/example/lunchtray/ui/EntreeMenuScreen.kt
1719447643
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lunchtray.ui.theme import androidx.compose.ui.graphics.Color val md_theme_light_primary = Color(0xFF6750A4) val md_theme_light_onPrimary = Color(0xFFFFFFFF) val md_theme_light_primaryContainer = Color(0xFFEADDFF) val md_theme_light_onPrimaryContainer = Color(0xFF21005D) val md_theme_light_secondary = Color(0xFF625B71) val md_theme_light_onSecondary = Color(0xFFFFFFFF) val md_theme_light_secondaryContainer = Color(0xFFE8DEF8) val md_theme_light_onSecondaryContainer = Color(0xFF1D192B) val md_theme_light_tertiary = Color(0xFF7D5260) val md_theme_light_onTertiary = Color(0xFFFFFFFF) val md_theme_light_tertiaryContainer = Color(0xFFFFD8E4) val md_theme_light_onTertiaryContainer = Color(0xFF31111D) val md_theme_light_error = Color(0xFFB3261E) val md_theme_light_onError = Color(0xFFFFFFFF) val md_theme_light_errorContainer = Color(0xFFF9DEDC) val md_theme_light_onErrorContainer = Color(0xFF410E0B) val md_theme_light_outline = Color(0xFF79747E) val md_theme_light_background = Color(0xFFFFFBFE) val md_theme_light_onBackground = Color(0xFF1C1B1F) val md_theme_light_surface = Color(0xFFFFFBFE) val md_theme_light_onSurface = Color(0xFF1C1B1F) val md_theme_light_surfaceVariant = Color(0xFFE7E0EC) val md_theme_light_onSurfaceVariant = Color(0xFF49454F) val md_theme_light_inverseSurface = Color(0xFF313033) val md_theme_light_inverseOnSurface = Color(0xFFF4EFF4) val md_theme_light_inversePrimary = Color(0xFFD0BCFF) val md_theme_light_surfaceTint = Color(0xFF6750A4) val md_theme_light_outlineVariant = Color(0xFFCAC4D0) val md_theme_light_scrim = Color(0xFF000000) val md_theme_dark_primary = Color(0xFFD0BCFF) val md_theme_dark_onPrimary = Color(0xFF381E72) val md_theme_dark_primaryContainer = Color(0xFF4F378B) val md_theme_dark_onPrimaryContainer = Color(0xFFEADDFF) val md_theme_dark_secondary = Color(0xFFCCC2DC) val md_theme_dark_onSecondary = Color(0xFF332D41) val md_theme_dark_secondaryContainer = Color(0xFF4A4458) val md_theme_dark_onSecondaryContainer = Color(0xFFE8DEF8) val md_theme_dark_tertiary = Color(0xFFEFB8C8) val md_theme_dark_onTertiary = Color(0xFF492532) val md_theme_dark_tertiaryContainer = Color(0xFF633B48) val md_theme_dark_onTertiaryContainer = Color(0xFFFFD8E4) val md_theme_dark_error = Color(0xFFF2B8B5) val md_theme_dark_onError = Color(0xFF601410) val md_theme_dark_errorContainer = Color(0xFF8C1D18) val md_theme_dark_onErrorContainer = Color(0xFFF9DEDC) val md_theme_dark_outline = Color(0xFF938F99) val md_theme_dark_background = Color(0xFF1C1B1F) val md_theme_dark_onBackground = Color(0xFFE6E1E5) val md_theme_dark_surface = Color(0xFF1C1B1F) val md_theme_dark_onSurface = Color(0xFFE6E1E5) val md_theme_dark_surfaceVariant = Color(0xFF49454F) val md_theme_dark_onSurfaceVariant = Color(0xFFCAC4D0) val md_theme_dark_inverseSurface = Color(0xFFE6E1E5) val md_theme_dark_inverseOnSurface = Color(0xFF313033) val md_theme_dark_inversePrimary = Color(0xFF6750A4) val md_theme_dark_surfaceTint = Color(0xFFD0BCFF) val md_theme_dark_outlineVariant = Color(0xFF49454F) val md_theme_dark_scrim = Color(0xFF000000)
AndroidLearning/compose-training-lunch-tray/app/src/main/java/com/example/lunchtray/ui/theme/Color.kt
1083366330
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lunchtray.ui.theme import android.app.Activity import android.os.Build import android.view.View import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val LightColorScheme = lightColorScheme( primary = md_theme_light_primary, onPrimary = md_theme_light_onPrimary, primaryContainer = md_theme_light_primaryContainer, onPrimaryContainer = md_theme_light_onPrimaryContainer, secondary = md_theme_light_secondary, onSecondary = md_theme_light_onSecondary, secondaryContainer = md_theme_light_secondaryContainer, onSecondaryContainer = md_theme_light_onSecondaryContainer, tertiary = md_theme_light_tertiary, onTertiary = md_theme_light_onTertiary, tertiaryContainer = md_theme_light_tertiaryContainer, onTertiaryContainer = md_theme_light_onTertiaryContainer, error = md_theme_light_error, onError = md_theme_light_onError, errorContainer = md_theme_light_errorContainer, onErrorContainer = md_theme_light_onErrorContainer, outline = md_theme_light_outline, background = md_theme_light_background, onBackground = md_theme_light_onBackground, surface = md_theme_light_surface, onSurface = md_theme_light_onSurface, surfaceVariant = md_theme_light_surfaceVariant, onSurfaceVariant = md_theme_light_onSurfaceVariant, inverseSurface = md_theme_light_inverseSurface, inverseOnSurface = md_theme_light_inverseOnSurface, inversePrimary = md_theme_light_inversePrimary, surfaceTint = md_theme_light_surfaceTint, outlineVariant = md_theme_light_outlineVariant, scrim = md_theme_light_scrim, ) private val DarkColorScheme = darkColorScheme( primary = md_theme_dark_primary, onPrimary = md_theme_dark_onPrimary, primaryContainer = md_theme_dark_primaryContainer, onPrimaryContainer = md_theme_dark_onPrimaryContainer, secondary = md_theme_dark_secondary, onSecondary = md_theme_dark_onSecondary, secondaryContainer = md_theme_dark_secondaryContainer, onSecondaryContainer = md_theme_dark_onSecondaryContainer, tertiary = md_theme_dark_tertiary, onTertiary = md_theme_dark_onTertiary, tertiaryContainer = md_theme_dark_tertiaryContainer, onTertiaryContainer = md_theme_dark_onTertiaryContainer, error = md_theme_dark_error, onError = md_theme_dark_onError, errorContainer = md_theme_dark_errorContainer, onErrorContainer = md_theme_dark_onErrorContainer, outline = md_theme_dark_outline, background = md_theme_dark_background, onBackground = md_theme_dark_onBackground, surface = md_theme_dark_surface, onSurface = md_theme_dark_onSurface, surfaceVariant = md_theme_dark_surfaceVariant, onSurfaceVariant = md_theme_dark_onSurfaceVariant, inverseSurface = md_theme_dark_inverseSurface, inverseOnSurface = md_theme_dark_inverseOnSurface, inversePrimary = md_theme_dark_inversePrimary, surfaceTint = md_theme_dark_surfaceTint, outlineVariant = md_theme_dark_outlineVariant, scrim = md_theme_dark_scrim, ) @Composable fun LunchTrayTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+, turned off for training purposes dynamicColor: Boolean = false, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { setUpEdgeToEdge(view, darkTheme) } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) } /** * Sets up edge-to-edge for the window of this [view]. The system icon colors are set to either * light or dark depending on whether the [darkTheme] is enabled or not. */ private fun setUpEdgeToEdge(view: View, darkTheme: Boolean) { val window = (view.context as Activity).window WindowCompat.setDecorFitsSystemWindows(window, false) window.statusBarColor = Color.Transparent.toArgb() val navigationBarColor = when { Build.VERSION.SDK_INT >= 29 -> Color.Transparent.toArgb() Build.VERSION.SDK_INT >= 26 -> Color(0xFF, 0xFF, 0xFF, 0x63).toArgb() // Min sdk version for this app is 24, this block is for SDK versions 24 and 25 else -> Color(0x00,0x00, 0x00, 0x50).toArgb() } window.navigationBarColor = navigationBarColor val controller = WindowCompat.getInsetsController(window, view) controller.isAppearanceLightStatusBars = !darkTheme controller.isAppearanceLightNavigationBars = !darkTheme }
AndroidLearning/compose-training-lunch-tray/app/src/main/java/com/example/lunchtray/ui/theme/Theme.kt
2773657517
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lunchtray.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) )
AndroidLearning/compose-training-lunch-tray/app/src/main/java/com/example/lunchtray/ui/theme/Type.kt
3063347909
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lunchtray.ui import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.tooling.preview.Preview import com.example.lunchtray.R import com.example.lunchtray.datasource.DataSource import com.example.lunchtray.model.MenuItem import com.example.lunchtray.model.MenuItem.SideDishItem @Composable fun SideDishMenuScreen( options: List<SideDishItem>, onCancelButtonClicked: () -> Unit, onNextButtonClicked: () -> Unit, onSelectionChanged: (SideDishItem) -> Unit, modifier: Modifier = Modifier ) { BaseMenuScreen( options = options, onCancelButtonClicked = onCancelButtonClicked, onNextButtonClicked = onNextButtonClicked, onSelectionChanged = onSelectionChanged as (MenuItem) -> Unit, modifier = modifier ) } @Preview @Composable fun SideDishMenuPreview(){ SideDishMenuScreen( options = DataSource.sideDishMenuItems, onNextButtonClicked = {}, onCancelButtonClicked = {}, onSelectionChanged = {}, modifier = Modifier .padding(dimensionResource(R.dimen.padding_medium)) .verticalScroll(rememberScrollState()) ) }
AndroidLearning/compose-training-lunch-tray/app/src/main/java/com/example/lunchtray/ui/SideDishMenuScreen.kt
2766041437
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lunchtray.ui import androidx.annotation.StringRes import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Button import androidx.compose.material3.Divider import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import com.example.lunchtray.R import com.example.lunchtray.datasource.DataSource import com.example.lunchtray.model.MenuItem import com.example.lunchtray.model.OrderUiState @Composable fun CheckoutScreen( orderUiState: OrderUiState, onNextButtonClicked: () -> Unit, onCancelButtonClicked: () -> Unit, modifier: Modifier = Modifier ) { Column( modifier = modifier, verticalArrangement = Arrangement.spacedBy(dimensionResource(R.dimen.padding_small)) ) { Text( text = stringResource(R.string.order_summary), fontWeight = FontWeight.Bold ) ItemSummary(item = orderUiState.entree, modifier = Modifier.fillMaxWidth()) ItemSummary(item = orderUiState.sideDish, modifier = Modifier.fillMaxWidth()) ItemSummary(item = orderUiState.accompaniment, modifier = Modifier.fillMaxWidth()) Divider( thickness = dimensionResource(R.dimen.thickness_divider), modifier = Modifier.padding(bottom = dimensionResource(R.dimen.padding_small)) ) OrderSubCost( resourceId = R.string.subtotal, price = orderUiState.itemTotalPrice.formatPrice(), Modifier.align(Alignment.End) ) OrderSubCost( resourceId = R.string.tax, price = orderUiState.orderTax.formatPrice(), Modifier.align(Alignment.End) ) Text( text = stringResource(R.string.total, orderUiState.orderTotalPrice.formatPrice()), modifier = Modifier.align(Alignment.End), fontWeight = FontWeight.Bold ) Row( modifier = Modifier .fillMaxWidth() .padding(dimensionResource(R.dimen.padding_medium)), horizontalArrangement = Arrangement.spacedBy(dimensionResource(R.dimen.padding_medium)) ){ OutlinedButton(modifier = Modifier.weight(1f), onClick = onCancelButtonClicked) { Text(stringResource(R.string.cancel).uppercase()) } Button( modifier = Modifier.weight(1f), onClick = onNextButtonClicked ) { Text(stringResource(R.string.submit).uppercase()) } } } } @Composable fun ItemSummary( item: MenuItem?, modifier: Modifier = Modifier ) { Row( modifier = modifier, horizontalArrangement = Arrangement.SpaceBetween ) { Text(item?.name ?: "") Text(item?.getFormattedPrice() ?: "") } } @Composable fun OrderSubCost( @StringRes resourceId: Int, price: String, modifier: Modifier = Modifier ) { Text( text = stringResource(resourceId, price), modifier = modifier ) } @Preview @Composable fun CheckoutScreenPreview() { CheckoutScreen( orderUiState = OrderUiState( entree = DataSource.entreeMenuItems[0], sideDish = DataSource.sideDishMenuItems[0], accompaniment = DataSource.accompanimentMenuItems[0], itemTotalPrice = 15.00, orderTax = 1.00, orderTotalPrice = 16.00 ), onNextButtonClicked = {}, onCancelButtonClicked = {}, modifier = Modifier .padding(dimensionResource(R.dimen.padding_medium)) .verticalScroll(rememberScrollState()) ) }
AndroidLearning/compose-training-lunch-tray/app/src/main/java/com/example/lunchtray/ui/CheckoutScreen.kt
3755612028
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lunchtray.datasource import com.example.lunchtray.model.MenuItem.AccompanimentItem import com.example.lunchtray.model.MenuItem.EntreeItem import com.example.lunchtray.model.MenuItem.SideDishItem /** * Map of available menu items to be displayed in the menu fragments. */ object DataSource { val entreeMenuItems = listOf( EntreeItem( name = "Cauliflower", description = "Whole cauliflower, brined, roasted, and deep fried", price = 7.00, ), EntreeItem( name = "Three Bean Chili", description = "Black beans, red beans, kidney beans, slow cooked, topped with onion", price = 4.00, ), EntreeItem( name = "Mushroom Pasta", description = "Penne pasta, mushrooms, basil, with plum tomatoes cooked in garlic " + "and olive oil", price = 5.50, ), EntreeItem( name = "Spicy Black Bean Skillet", description = "Seasonal vegetables, black beans, house spice blend, served with " + "avocado and quick pickled onions", price = 5.50, ) ) val sideDishMenuItems = listOf( SideDishItem( name = "Summer Salad", description = "Heirloom tomatoes, butter lettuce, peaches, avocado, balsamic dressing", price = 2.50, ), SideDishItem( name = "Butternut Squash Soup", description = "Roasted butternut squash, roasted peppers, chili oil", price = 3.00, ), SideDishItem( name = "Spicy Potatoes", description = "Marble potatoes, roasted, and fried in house spice blend", price = 2.00, ), SideDishItem( name = "Coconut Rice", description = "Rice, coconut milk, lime, and sugar", price = 1.50, ) ) val accompanimentMenuItems = listOf( AccompanimentItem( name = "Lunch Roll", description = "Fresh baked roll made in house", price = 0.50, ), AccompanimentItem( name = "Mixed Berries", description = "Strawberries, blueberries, raspberries, and huckleberries", price = 1.00, ), AccompanimentItem( name = "Pickled Veggies", description = "Pickled cucumbers and carrots, made in house", price = 0.50, ) ) }
AndroidLearning/compose-training-lunch-tray/app/src/main/java/com/example/lunchtray/datasource/DataSource.kt
3055318248
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lunchtray import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import com.example.lunchtray.ui.theme.LunchTrayTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { LunchTrayTheme { LunchTrayApp() } } } }
AndroidLearning/compose-training-lunch-tray/app/src/main/java/com/example/lunchtray/MainActivity.kt
3362873378
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lunchtray import androidx.annotation.StringRes import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import com.example.lunchtray.datasource.DataSource import com.example.lunchtray.ui.AccompanimentMenuScreen import com.example.lunchtray.ui.CheckoutScreen import com.example.lunchtray.ui.EntreeMenuScreen import com.example.lunchtray.ui.OrderViewModel import com.example.lunchtray.ui.SideDishMenuScreen import com.example.lunchtray.ui.StartOrderScreen enum class LaunchTrayScreen(@StringRes val title: Int) { START(title = R.string.app_name), ENTREE_MENU(title = R.string.choose_entree), SIDE_DISH_MENU(title = R.string.choose_side_dish), ACCOMPANIMENT_MENU(title = R.string.choose_accompaniment), CHECKOUT(title = R.string.order_checkout) } @OptIn(ExperimentalMaterial3Api::class) @Composable fun LaunchTrayAppBar( currentScreen: LaunchTrayScreen, canNavigateBack: Boolean, navigateUp: () -> Unit, modifier: Modifier = Modifier ) { CenterAlignedTopAppBar( title = { Text(stringResource(id = currentScreen.title)) }, modifier = modifier, navigationIcon = { if (canNavigateBack) { IconButton(onClick = navigateUp) { Icon( imageVector = Icons.Filled.ArrowBack, contentDescription = stringResource(R.string.back_button) ) } } } ) } @OptIn(ExperimentalMaterial3Api::class) @Composable fun LunchTrayApp( navController: NavHostController = rememberNavController(), viewModel: OrderViewModel = viewModel() ) { val backStackEntry by navController.currentBackStackEntryAsState() val currentScreen = LaunchTrayScreen.valueOf( backStackEntry?.destination?.route ?: LaunchTrayScreen.START.name ) Scaffold( topBar = { LaunchTrayAppBar( currentScreen = currentScreen, canNavigateBack = navController.previousBackStackEntry != null, navigateUp = { navController.navigateUp() }) } ) { innerPadding -> val uiState by viewModel.uiState.collectAsState() NavHost( navController = navController, startDestination = LaunchTrayScreen.START.name, modifier = Modifier.padding(innerPadding) ) { composable( LaunchTrayScreen.START.name ) { StartOrderScreen( onStartOrderButtonClicked = { navController.navigate(LaunchTrayScreen.ENTREE_MENU.name) }, modifier = Modifier.fillMaxSize() ) } composable( route = LaunchTrayScreen.ENTREE_MENU.name ) { EntreeMenuScreen( options = DataSource.entreeMenuItems, onCancelButtonClicked = { navigateToHome(navController) }, onNextButtonClicked = { navController.navigate(LaunchTrayScreen.SIDE_DISH_MENU.name) }, onSelectionChanged = { viewModel.updateEntree(it) }, modifier = Modifier.fillMaxSize() ) } composable( LaunchTrayScreen.SIDE_DISH_MENU.name, ) { SideDishMenuScreen( options = DataSource.sideDishMenuItems, onCancelButtonClicked = { navigateToHome(navController) }, onNextButtonClicked = { navController.navigate(LaunchTrayScreen.ACCOMPANIMENT_MENU.name) }, onSelectionChanged = { viewModel.updateSideDish(it) }, modifier = Modifier.fillMaxSize() ) } composable( LaunchTrayScreen.CHECKOUT.name ) { CheckoutScreen( modifier = Modifier.fillMaxSize(), orderUiState = uiState, onNextButtonClicked = { navigateToHome(navController) }, onCancelButtonClicked = { navigateToHome(navController) }) } composable( LaunchTrayScreen.ACCOMPANIMENT_MENU.name ) { AccompanimentMenuScreen( options = DataSource.accompanimentMenuItems, onCancelButtonClicked = { navigateToHome(navController) }, onNextButtonClicked = { navController.navigate(LaunchTrayScreen.CHECKOUT.name) }, onSelectionChanged = { viewModel.updateAccompaniment(it) }, modifier = Modifier.fillMaxSize() ) } } } } fun navigateToHome(navController: NavHostController) { navController.popBackStack(LaunchTrayScreen.START.name, false) }
AndroidLearning/compose-training-lunch-tray/app/src/main/java/com/example/lunchtray/LunchTrayScreen.kt
1454848736
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lunchtray.model import java.text.NumberFormat sealed class MenuItem( open val name: String, open val description: String, open val price: Double ) { /** * Getter method for price. * Includes formatting. */ data class EntreeItem( override val name: String, override val description: String, override val price: Double ) : MenuItem(name, description, price) data class SideDishItem( override val name: String, override val description: String, override val price: Double ) : MenuItem(name, description, price) data class AccompanimentItem( override val name: String, override val description: String, override val price: Double ) : MenuItem(name, description, price) /** * Getter method for price. * Includes formatting. */ fun getFormattedPrice(): String = NumberFormat.getCurrencyInstance().format(price) }
AndroidLearning/compose-training-lunch-tray/app/src/main/java/com/example/lunchtray/model/MenuItem.kt
2124744105
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lunchtray.model data class OrderUiState( // Entree Selection val entree: MenuItem.EntreeItem? = null, val sideDish: MenuItem.SideDishItem? = null, val accompaniment: MenuItem.AccompanimentItem? = null, val itemTotalPrice: Double = 0.0, val orderTax: Double = 0.0, val orderTotalPrice: Double = 0.0 )
AndroidLearning/compose-training-lunch-tray/app/src/main/java/com/example/lunchtray/model/OrderUiState.kt
3341595473
package com.example.cupcake.test import androidx.activity.ComponentActivity import androidx.annotation.StringRes import androidx.compose.ui.test.SemanticsNodeInteraction import androidx.compose.ui.test.junit4.AndroidComposeTestRule import androidx.compose.ui.test.onNodeWithText import androidx.test.ext.junit.rules.ActivityScenarioRule fun <A : ComponentActivity> AndroidComposeTestRule<ActivityScenarioRule<A>, A>.onNodeWithStringId(@StringRes id: Int): SemanticsNodeInteraction = onNodeWithText(activity.getString(id))
AndroidLearning/compose-training-cupcake/app/src/androidTest/java/com/example/cupcake/test/ComposeRuleExtensions.kt
3917163553
package com.example.cupcake.test import androidx.navigation.NavController import org.junit.Assert.assertEquals fun NavController.assertCurrentRouteName(expectedRouteName: String) { assertEquals(expectedRouteName, currentBackStackEntry?.destination?.route) }
AndroidLearning/compose-training-cupcake/app/src/androidTest/java/com/example/cupcake/test/ScreenAssertions.kt
378215826
package com.example.cupcake.test import androidx.activity.ComponentActivity import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.navigation.compose.ComposeNavigator import androidx.navigation.testing.TestNavHostController import com.example.cupcake.CupcakeApp import com.example.cupcake.CupcakeScreen import com.example.cupcake.R import org.junit.Before import org.junit.Rule import org.junit.Test import java.text.SimpleDateFormat import java.util.Calendar import java.util.Locale class CupcakeScreenNavigationTest { @get:Rule val composeTestRule = createAndroidComposeRule<ComponentActivity>() private lateinit var navController: TestNavHostController @Before fun setupCupcakeNavHost() { composeTestRule.setContent { navController = TestNavHostController(LocalContext.current).apply { navigatorProvider.addNavigator(ComposeNavigator()) } CupcakeApp(navController = navController) } } @Test fun cupcakeNavHost_verifyStartDestination() { navController.assertCurrentRouteName(CupcakeScreen.Start.name) } @Test fun cupcakeNavHost_verifyBackNavigationNotShownOnStartOrderScreen() { val backText = composeTestRule.activity.getString(R.string.back_button) composeTestRule.onNodeWithContentDescription(backText).assertDoesNotExist() } @Test fun cupcakeNavHost_clickOneCupcake_navigatesToSelectFlavorScreen() { composeTestRule.onNodeWithStringId(R.string.one_cupcake) .performClick() navController.assertCurrentRouteName(CupcakeScreen.Flavor.name) } @Test fun cupcakeNavHost_clickNextOnFlavorScreen_navigatesToPickupScreen() { navigateToFlavorScreen() composeTestRule.onNodeWithStringId(R.string.next) .performClick() navController.assertCurrentRouteName(CupcakeScreen.Pickup.name) } @Test fun cupcakeNavHost_clickBackOnFlavorScreen_navigatesToStartOrderScreen() { navigateToFlavorScreen() performNavigateUp() navController.assertCurrentRouteName(CupcakeScreen.Start.name) } @Test fun cupcakeNavHost_clickCancelOnFlavorScreen_navigatesToStartOrderScreen() { navigateToFlavorScreen() composeTestRule.onNodeWithStringId(R.string.cancel) .performClick() navController.assertCurrentRouteName(CupcakeScreen.Start.name) } @Test fun cupcakeNavHost_clickNextOnPickupScreen_navigatesToSummaryScreen() { navigateToPickupScreen() composeTestRule.onNodeWithText(getFormattedDate()) .performClick() composeTestRule.onNodeWithStringId(R.string.next) .performClick() navController.assertCurrentRouteName(CupcakeScreen.Summary.name) } @Test fun cupcakeNavHost_clickBackOnPickupScreen_navigatesToFlavorScreen() { navigateToPickupScreen() performNavigateUp() navController.assertCurrentRouteName(CupcakeScreen.Flavor.name) } @Test fun cupcakeNavHost_clickCancelOnPickupScreen_navigatesToStartOrderScreen() { navigateToPickupScreen() composeTestRule.onNodeWithStringId(R.string.cancel) .performClick() navController.assertCurrentRouteName(CupcakeScreen.Start.name) } @Test fun cupcakeNavHost_clickCancelOnSummaryScreen_navigatesToStartOrderScreen() { navigateToSummaryScreen() composeTestRule.onNodeWithStringId(R.string.cancel) .performClick() navController.assertCurrentRouteName(CupcakeScreen.Start.name) } private fun navigateToFlavorScreen() { composeTestRule.onNodeWithStringId(R.string.one_cupcake) .performClick() composeTestRule.onNodeWithStringId(R.string.chocolate) .performClick() } private fun navigateToPickupScreen() { navigateToFlavorScreen() composeTestRule.onNodeWithStringId(R.string.next) .performClick() } private fun navigateToSummaryScreen() { navigateToPickupScreen() composeTestRule.onNodeWithText(getFormattedDate()) .performClick() composeTestRule.onNodeWithStringId(R.string.next) .performClick() } private fun performNavigateUp() { val backText = composeTestRule.activity.getString(R.string.back_button) composeTestRule.onNodeWithContentDescription(backText).performClick() } private fun getFormattedDate(): String { val calendar = Calendar.getInstance() calendar.add(java.util.Calendar.DATE, 1) val formatter = SimpleDateFormat("E MMM d", Locale.getDefault()) return formatter.format(calendar.time) } }
AndroidLearning/compose-training-cupcake/app/src/androidTest/java/com/example/cupcake/test/CupcakeScreenNavigationTest.kt
3527858392
package com.example.cupcake.test import androidx.activity.ComponentActivity import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertIsEnabled import androidx.compose.ui.test.assertIsNotEnabled import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import com.example.cupcake.R import com.example.cupcake.ui.SelectOptionScreen import org.junit.Rule import org.junit.Test class CupcakeOrderScreenTest { @get:Rule val composeTestRule = createAndroidComposeRule<ComponentActivity>() @Test fun selectOptionScreen_verifyContent() { val flavors = listOf("Vanilla", "Chocolate", "Hazelnut", "Cookie", "Mango") val subtotal = "$100" composeTestRule.setContent { SelectOptionScreen( subtotal = subtotal, options = flavors ) } flavors.forEach { composeTestRule.onNodeWithText(it).assertIsDisplayed() } composeTestRule.onNodeWithText( composeTestRule.activity.getString( R.string.subtotal_price, subtotal ) ).assertIsDisplayed() composeTestRule.onNodeWithStringId(R.string.next).assertIsNotEnabled() composeTestRule.onNodeWithText(flavors[0]).performClick() composeTestRule.onNodeWithStringId(R.string.next).assertIsEnabled() } }
AndroidLearning/compose-training-cupcake/app/src/androidTest/java/com/example/cupcake/test/CupcakeOrderScreenTest.kt
2485442232
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.cupcake.ui import androidx.lifecycle.ViewModel import com.example.cupcake.data.OrderUiState import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import java.text.NumberFormat import java.text.SimpleDateFormat import java.util.Calendar import java.util.Locale /** Price for a single cupcake */ private const val PRICE_PER_CUPCAKE = 2.00 /** Additional cost for same day pickup of an order */ private const val PRICE_FOR_SAME_DAY_PICKUP = 3.00 /** * [OrderViewModel] holds information about a cupcake order in terms of quantity, flavor, and * pickup date. It also knows how to calculate the total price based on these order details. */ class OrderViewModel : ViewModel() { /** * Cupcake state for this order */ private val _uiState = MutableStateFlow(OrderUiState(pickupOptions = pickupOptions())) val uiState: StateFlow<OrderUiState> = _uiState.asStateFlow() /** * Set the quantity [numberCupcakes] of cupcakes for this order's state and update the price */ fun setQuantity(numberCupcakes: Int) { _uiState.update { currentState -> currentState.copy( quantity = numberCupcakes, price = calculatePrice(quantity = numberCupcakes) ) } } /** * Set the [desiredFlavor] of cupcakes for this order's state. * Only 1 flavor can be selected for the whole order. */ fun setFlavor(desiredFlavor: String) { _uiState.update { currentState -> currentState.copy(flavor = desiredFlavor) } } /** * Set the [pickupDate] for this order's state and update the price */ fun setDate(pickupDate: String) { _uiState.update { currentState -> currentState.copy( date = pickupDate, price = calculatePrice(pickupDate = pickupDate) ) } } /** * Reset the order state */ fun resetOrder() { _uiState.value = OrderUiState(pickupOptions = pickupOptions()) } /** * Returns the calculated price based on the order details. */ private fun calculatePrice( quantity: Int = _uiState.value.quantity, pickupDate: String = _uiState.value.date ): String { var calculatedPrice = quantity * PRICE_PER_CUPCAKE // If the user selected the first option (today) for pickup, add the surcharge if (pickupOptions()[0] == pickupDate) { calculatedPrice += PRICE_FOR_SAME_DAY_PICKUP } val formattedPrice = NumberFormat.getCurrencyInstance().format(calculatedPrice) return formattedPrice } /** * Returns a list of date options starting with the current date and the following 3 dates. */ private fun pickupOptions(): List<String> { val dateOptions = mutableListOf<String>() val formatter = SimpleDateFormat("E MMM d", Locale.getDefault()) val calendar = Calendar.getInstance() // add current date and the following 3 dates. repeat(4) { dateOptions.add(formatter.format(calendar.time)) calendar.add(Calendar.DATE, 1) } return dateOptions } }
AndroidLearning/compose-training-cupcake/app/src/main/java/com/example/cupcake/ui/OrderViewModel.kt
97958473
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.cupcake.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.selection.selectable import androidx.compose.material3.Button import androidx.compose.material3.Divider import androidx.compose.material3.OutlinedButton import androidx.compose.material3.RadioButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import com.example.cupcake.R import com.example.cupcake.ui.components.FormattedPriceLabel import com.example.cupcake.ui.theme.CupcakeTheme /** * Composable that displays the list of items as [RadioButton] options, * [onSelectionChanged] lambda that notifies the parent composable when a new value is selected, * [onCancelButtonClicked] lambda that cancels the order when user clicks cancel and * [onNextButtonClicked] lambda that triggers the navigation to next screen */ @Composable fun SelectOptionScreen( subtotal: String, options: List<String>, onSelectionChanged: (String) -> Unit = {}, onCancelButtonClicked: () -> Unit = {}, onNextButtonClicked: () -> Unit = {}, modifier: Modifier = Modifier ) { var selectedValue by rememberSaveable { mutableStateOf("") } Column( modifier = modifier, verticalArrangement = Arrangement.SpaceBetween ) { Column(modifier = Modifier.padding(dimensionResource(R.dimen.padding_medium))) { options.forEach { item -> Row( modifier = Modifier.selectable( selected = selectedValue == item, onClick = { selectedValue = item onSelectionChanged(item) } ), verticalAlignment = Alignment.CenterVertically ) { RadioButton( selected = selectedValue == item, onClick = { selectedValue = item onSelectionChanged(item) } ) Text(item) } } Divider( thickness = dimensionResource(R.dimen.thickness_divider), modifier = Modifier.padding(bottom = dimensionResource(R.dimen.padding_medium)) ) FormattedPriceLabel( subtotal = subtotal, modifier = Modifier .align(Alignment.End) .padding( top = dimensionResource(R.dimen.padding_medium), bottom = dimensionResource(R.dimen.padding_medium) ) ) } Row( modifier = Modifier .fillMaxWidth() .padding(dimensionResource(R.dimen.padding_medium)), horizontalArrangement = Arrangement.spacedBy(dimensionResource(R.dimen.padding_medium)), verticalAlignment = Alignment.Bottom ) { OutlinedButton( modifier = Modifier.weight(1f), onClick = { onCancelButtonClicked() } ) { Text(stringResource(R.string.cancel)) } Button( modifier = Modifier.weight(1f), // the button is enabled when the user makes a selection enabled = selectedValue.isNotEmpty(), onClick = { onNextButtonClicked() } ) { Text(stringResource(R.string.next)) } } } } @Preview @Composable fun SelectOptionPreview() { CupcakeTheme { SelectOptionScreen( subtotal = "299.99", options = listOf("Option 1", "Option 2", "Option 3", "Option 4"), modifier = Modifier.fillMaxHeight() ) } }
AndroidLearning/compose-training-cupcake/app/src/main/java/com/example/cupcake/ui/SelectOptionScreen.kt
294905089
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.cupcake.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button import androidx.compose.material3.Divider import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import com.example.cupcake.R import com.example.cupcake.data.OrderUiState import com.example.cupcake.ui.components.FormattedPriceLabel import com.example.cupcake.ui.theme.CupcakeTheme /** * This composable expects [orderUiState] that represents the order state, [onCancelButtonClicked] * lambda that triggers canceling the order and passes the final order to [onSendButtonClicked] * lambda */ @Composable fun OrderSummaryScreen( orderUiState: OrderUiState, onCancelButtonClicked: () -> Unit, onSentButtonClicked: (String, String) -> Unit, modifier: Modifier = Modifier ) { val resources = LocalContext.current.resources val numberOfCupcakes = resources.getQuantityString( R.plurals.cupcakes, orderUiState.quantity, orderUiState.quantity ) //Load and format a string resource with the parameters. val orderSummary = stringResource( R.string.order_details, numberOfCupcakes, orderUiState.flavor, orderUiState.date, orderUiState.quantity ) val newOrder = stringResource(R.string.new_cupcake_order) //Create a list of order summary to display val items = listOf( // Summary line 1: display selected quantity Pair(stringResource(R.string.quantity), numberOfCupcakes), // Summary line 2: display selected flavor Pair(stringResource(R.string.flavor), orderUiState.flavor), // Summary line 3: display selected pickup date Pair(stringResource(R.string.pickup_date), orderUiState.date) ) Column( modifier = modifier, verticalArrangement = Arrangement.SpaceBetween ) { Column( modifier = Modifier.padding(dimensionResource(R.dimen.padding_medium)), verticalArrangement = Arrangement.spacedBy(dimensionResource(R.dimen.padding_small)) ) { items.forEach { item -> Text(item.first.uppercase()) Text(text = item.second, fontWeight = FontWeight.Bold) Divider(thickness = dimensionResource(R.dimen.thickness_divider)) } Spacer(modifier = Modifier.height(dimensionResource(R.dimen.padding_small))) FormattedPriceLabel( subtotal = orderUiState.price, modifier = Modifier.align(Alignment.End) ) } Row( modifier = Modifier.padding(dimensionResource(R.dimen.padding_medium)) ) { Column( verticalArrangement = Arrangement.spacedBy(dimensionResource(R.dimen.padding_small)) ) { Button( modifier = Modifier.fillMaxWidth(), onClick = { onSentButtonClicked(newOrder, orderSummary) } ) { Text(stringResource(R.string.send)) } OutlinedButton( modifier = Modifier.fillMaxWidth(), onClick = { onCancelButtonClicked() } ) { Text(stringResource(R.string.cancel)) } } } } } @Preview @Composable fun OrderSummaryPreview() { CupcakeTheme { OrderSummaryScreen( orderUiState = OrderUiState(0, "Test", "Test", "$300.00"), {}, { a, b -> }, modifier = Modifier.fillMaxHeight() ) } }
AndroidLearning/compose-training-cupcake/app/src/main/java/com/example/cupcake/ui/SummaryScreen.kt
1274787079
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.cupcake.ui import androidx.annotation.StringRes import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.widthIn import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.cupcake.R import com.example.cupcake.data.DataSource import com.example.cupcake.ui.theme.CupcakeTheme /** * Composable that allows the user to select the desired cupcake quantity and expects * [onNextButtonClicked] lambda that expects the selected quantity and triggers the navigation to * next screen */ @Composable fun StartOrderScreen( quantityOptions: List<Pair<Int, Int>>, onNextButtonClicked: (Int) -> Unit, modifier: Modifier = Modifier ) { Column( modifier = modifier, verticalArrangement = Arrangement.SpaceBetween ) { Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(dimensionResource(R.dimen.padding_small)) ) { Spacer(modifier = Modifier.height(dimensionResource(R.dimen.padding_medium))) Image( painter = painterResource(R.drawable.cupcake), contentDescription = null, modifier = Modifier.width(300.dp) ) Spacer(modifier = Modifier.height(dimensionResource(R.dimen.padding_medium))) Text( text = stringResource(R.string.order_cupcakes), style = MaterialTheme.typography.headlineSmall ) Spacer(modifier = Modifier.height(dimensionResource(R.dimen.padding_small))) } Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy( dimensionResource(id = R.dimen.padding_medium) ) ) { quantityOptions.forEach { item -> SelectQuantityButton( labelResourceId = item.first, onClick = {onNextButtonClicked(item.second)} ) } } } } /** * Customizable button composable that displays the [labelResourceId] * and triggers [onClick] lambda when this composable is clicked */ @Composable fun SelectQuantityButton( @StringRes labelResourceId: Int, onClick: () -> Unit, modifier: Modifier = Modifier ) { Button( onClick = onClick, modifier = modifier.widthIn(min = 250.dp) ) { Text(stringResource(labelResourceId)) } } @Preview @Composable fun StartOrderPreview() { CupcakeTheme { StartOrderScreen( quantityOptions = DataSource.quantityOptions, onNextButtonClicked = {}, modifier = Modifier .fillMaxSize() .padding(dimensionResource(R.dimen.padding_medium)) ) } }
AndroidLearning/compose-training-cupcake/app/src/main/java/com/example/cupcake/ui/StartOrderScreen.kt
1249653009
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.cupcake.ui.components import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import com.example.cupcake.R /** * Composable that displays formatted [price] that will be formatted and displayed on screen */ @Composable fun FormattedPriceLabel(subtotal: String, modifier: Modifier = Modifier) { Text( text = stringResource(R.string.subtotal_price, subtotal), modifier = modifier, style = MaterialTheme.typography.headlineSmall ) }
AndroidLearning/compose-training-cupcake/app/src/main/java/com/example/cupcake/ui/components/CommonUi.kt
3238236991
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.cupcake.ui.theme import androidx.compose.ui.graphics.Color val md_theme_light_primary = Color(0xFF984062) val md_theme_light_onPrimary = Color(0xFFFFFFFF) val md_theme_light_primaryContainer = Color(0xFFFFD9E2) val md_theme_light_onPrimaryContainer = Color(0xFF3E001E) val md_theme_light_secondary = Color(0xFF74565F) val md_theme_light_onSecondary = Color(0xFFFFFFFF) val md_theme_light_secondaryContainer = Color(0xFFFFD9E2) val md_theme_light_onSecondaryContainer = Color(0xFF2B151C) val md_theme_light_tertiary = Color(0xFF7C5635) val md_theme_light_onTertiary = Color(0xFFFFFFFF) val md_theme_light_tertiaryContainer = Color(0xFFFFDCC2) val md_theme_light_onTertiaryContainer = Color(0xFF2E1500) val md_theme_light_error = Color(0xFFBA1A1A) val md_theme_light_errorContainer = Color(0xFFFFDAD6) val md_theme_light_onError = Color(0xFFFFFFFF) val md_theme_light_onErrorContainer = Color(0xFF410002) val md_theme_light_background = Color(0xFFFFFBFF) val md_theme_light_onBackground = Color(0xFF201A1B) val md_theme_light_surface = Color(0xFFFFFBFF) val md_theme_light_onSurface = Color(0xFF201A1B) val md_theme_light_surfaceVariant = Color(0xFFF2DDE2) val md_theme_light_onSurfaceVariant = Color(0xFF514347) val md_theme_light_outline = Color(0xFF837377) val md_theme_light_inverseOnSurface = Color(0xFFFAEEEF) val md_theme_light_inverseSurface = Color(0xFF352F30) val md_theme_light_inversePrimary = Color(0xFFFFB0C9) val md_theme_light_surfaceTint = Color(0xFF984062) val md_theme_light_outlineVariant = Color(0xFFD5C2C6) val md_theme_light_scrim = Color(0xFF000000) val md_theme_dark_primary = Color(0xFFFFB0C9) val md_theme_dark_onPrimary = Color(0xFF5E1133) val md_theme_dark_primaryContainer = Color(0xFF7B294A) val md_theme_dark_onPrimaryContainer = Color(0xFFFFD9E2) val md_theme_dark_secondary = Color(0xFFE2BDC7) val md_theme_dark_onSecondary = Color(0xFF422931) val md_theme_dark_secondaryContainer = Color(0xFF5A3F47) val md_theme_dark_onSecondaryContainer = Color(0xFFFFD9E2) val md_theme_dark_tertiary = Color(0xFFEFBD94) val md_theme_dark_onTertiary = Color(0xFF48290C) val md_theme_dark_tertiaryContainer = Color(0xFF623F20) val md_theme_dark_onTertiaryContainer = Color(0xFFFFDCC2) val md_theme_dark_error = Color(0xFFFFB4AB) val md_theme_dark_errorContainer = Color(0xFF93000A) val md_theme_dark_onError = Color(0xFF690005) val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6) val md_theme_dark_background = Color(0xFF201A1B) val md_theme_dark_onBackground = Color(0xFFEBE0E1) val md_theme_dark_surface = Color(0xFF201A1B) val md_theme_dark_onSurface = Color(0xFFEBE0E1) val md_theme_dark_surfaceVariant = Color(0xFF514347) val md_theme_dark_onSurfaceVariant = Color(0xFFD5C2C6) val md_theme_dark_outline = Color(0xFF9E8C90) val md_theme_dark_inverseOnSurface = Color(0xFF201A1B) val md_theme_dark_inverseSurface = Color(0xFFEBE0E1) val md_theme_dark_inversePrimary = Color(0xFF984062) val md_theme_dark_surfaceTint = Color(0xFFFFB0C9) val md_theme_dark_outlineVariant = Color(0xFF514347) val md_theme_dark_scrim = Color(0xFF000000)
AndroidLearning/compose-training-cupcake/app/src/main/java/com/example/cupcake/ui/theme/Color.kt
3674021801
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.cupcake.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val LightColors = lightColorScheme( primary = md_theme_light_primary, onPrimary = md_theme_light_onPrimary, primaryContainer = md_theme_light_primaryContainer, onPrimaryContainer = md_theme_light_onPrimaryContainer, secondary = md_theme_light_secondary, onSecondary = md_theme_light_onSecondary, secondaryContainer = md_theme_light_secondaryContainer, onSecondaryContainer = md_theme_light_onSecondaryContainer, tertiary = md_theme_light_tertiary, onTertiary = md_theme_light_onTertiary, tertiaryContainer = md_theme_light_tertiaryContainer, onTertiaryContainer = md_theme_light_onTertiaryContainer, error = md_theme_light_error, errorContainer = md_theme_light_errorContainer, onError = md_theme_light_onError, onErrorContainer = md_theme_light_onErrorContainer, background = md_theme_light_background, onBackground = md_theme_light_onBackground, surface = md_theme_light_surface, onSurface = md_theme_light_onSurface, surfaceVariant = md_theme_light_surfaceVariant, onSurfaceVariant = md_theme_light_onSurfaceVariant, outline = md_theme_light_outline, inverseOnSurface = md_theme_light_inverseOnSurface, inverseSurface = md_theme_light_inverseSurface, inversePrimary = md_theme_light_inversePrimary, surfaceTint = md_theme_light_surfaceTint, outlineVariant = md_theme_light_outlineVariant, scrim = md_theme_light_scrim, ) private val DarkColors = darkColorScheme( primary = md_theme_dark_primary, onPrimary = md_theme_dark_onPrimary, primaryContainer = md_theme_dark_primaryContainer, onPrimaryContainer = md_theme_dark_onPrimaryContainer, secondary = md_theme_dark_secondary, onSecondary = md_theme_dark_onSecondary, secondaryContainer = md_theme_dark_secondaryContainer, onSecondaryContainer = md_theme_dark_onSecondaryContainer, tertiary = md_theme_dark_tertiary, onTertiary = md_theme_dark_onTertiary, tertiaryContainer = md_theme_dark_tertiaryContainer, onTertiaryContainer = md_theme_dark_onTertiaryContainer, error = md_theme_dark_error, errorContainer = md_theme_dark_errorContainer, onError = md_theme_dark_onError, onErrorContainer = md_theme_dark_onErrorContainer, background = md_theme_dark_background, onBackground = md_theme_dark_onBackground, surface = md_theme_dark_surface, onSurface = md_theme_dark_onSurface, surfaceVariant = md_theme_dark_surfaceVariant, onSurfaceVariant = md_theme_dark_onSurfaceVariant, outline = md_theme_dark_outline, inverseOnSurface = md_theme_dark_inverseOnSurface, inverseSurface = md_theme_dark_inverseSurface, inversePrimary = md_theme_dark_inversePrimary, surfaceTint = md_theme_dark_surfaceTint, outlineVariant = md_theme_dark_outlineVariant, scrim = md_theme_dark_scrim, ) @Composable fun CupcakeTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ but turned off for training purposes dynamicColor: Boolean = false, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColors else -> LightColors } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
AndroidLearning/compose-training-cupcake/app/src/main/java/com/example/cupcake/ui/theme/Theme.kt
4049201284
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.cupcake.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) )
AndroidLearning/compose-training-cupcake/app/src/main/java/com/example/cupcake/ui/theme/Type.kt
925331214
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.cupcake import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import com.example.cupcake.ui.theme.CupcakeTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { enableEdgeToEdge() super.onCreate(savedInstanceState) setContent { CupcakeTheme { CupcakeApp() } } } }
AndroidLearning/compose-training-cupcake/app/src/main/java/com/example/cupcake/MainActivity.kt
3033576811
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.cupcake import android.content.Context import android.content.Intent import androidx.annotation.StringRes import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import com.example.cupcake.data.DataSource import com.example.cupcake.ui.OrderSummaryScreen import com.example.cupcake.ui.OrderViewModel import com.example.cupcake.ui.SelectOptionScreen import com.example.cupcake.ui.StartOrderScreen enum class CupcakeScreen(@StringRes val title: Int) { Start(R.string.app_name), Flavor(R.string.choose_flavor), Pickup(R.string.choose_pickup_date), Summary(R.string.order_summary) } private fun shareOrder(context: Context, subject: String, summary: String) { val intent = Intent(Intent.ACTION_SEND).apply { type = "text/plain" putExtra(Intent.EXTRA_SUBJECT, subject) putExtra(Intent.EXTRA_TEXT, summary) } context.startActivity( Intent.createChooser( intent, context.getString(R.string.new_cupcake_order) ) ) } /** * Composable that displays the topBar and displays back button if back navigation is possible. */ @Composable fun CupcakeAppBar( currentScreen: CupcakeScreen, canNavigateBack: Boolean, navigateUp: () -> Unit, modifier: Modifier = Modifier ) { TopAppBar( title = { Text(stringResource(id = currentScreen.title)) }, colors = TopAppBarDefaults.mediumTopAppBarColors( containerColor = MaterialTheme.colorScheme.primaryContainer ), modifier = modifier, navigationIcon = { if (canNavigateBack) { IconButton(onClick = navigateUp) { Icon( imageVector = Icons.Filled.ArrowBack, contentDescription = stringResource(R.string.back_button) ) } } } ) } @Composable fun CupcakeApp( viewModel: OrderViewModel = viewModel(), navController: NavHostController = rememberNavController() ) { val backStackEntry by navController.currentBackStackEntryAsState() val currentScreen = CupcakeScreen.valueOf( backStackEntry?.destination?.route ?: CupcakeScreen.Start.name ) Scaffold( topBar = { CupcakeAppBar( currentScreen = currentScreen, canNavigateBack = navController.previousBackStackEntry != null, navigateUp = { navController.navigateUp() } ) } ) { innerPadding -> val uiState by viewModel.uiState.collectAsState() NavHost( navController = navController, startDestination = CupcakeScreen.Start.name, modifier = Modifier.padding(innerPadding) ) { composable(route = CupcakeScreen.Start.name) { StartOrderScreen( quantityOptions = DataSource.quantityOptions, onNextButtonClicked = { viewModel.setQuantity(it) navController.navigate(CupcakeScreen.Flavor.name) }, modifier = Modifier .fillMaxSize() .padding(dimensionResource(id = R.dimen.padding_medium)) ) } composable( route = CupcakeScreen.Flavor.name, ) { val context = LocalContext.current SelectOptionScreen( subtotal = uiState.price, options = DataSource.flavors.map { id -> context.resources.getString(id) }, onSelectionChanged = { viewModel.setFlavor(it) }, onCancelButtonClicked = { cancelOrderAndNavigateToStart( viewModel, navController ) }, onNextButtonClicked = { navController.navigate(CupcakeScreen.Pickup.name) }, modifier = Modifier.fillMaxHeight() ) } composable( route = CupcakeScreen.Pickup.name ) { SelectOptionScreen( subtotal = uiState.price, options = uiState.pickupOptions, onNextButtonClicked = { navController.navigate(CupcakeScreen.Summary.name) }, onCancelButtonClicked = { cancelOrderAndNavigateToStart( viewModel, navController ) }, onSelectionChanged = { viewModel.setDate(it) }, modifier = Modifier.fillMaxHeight() ) } composable( route = CupcakeScreen.Summary.name ) { val context = LocalContext.current OrderSummaryScreen( orderUiState = uiState, onSentButtonClicked = { sub, summ -> shareOrder(context, sub, summ) }, onCancelButtonClicked = { cancelOrderAndNavigateToStart( viewModel, navController ) }, modifier = Modifier.fillMaxHeight() ) } } } } private fun cancelOrderAndNavigateToStart( viewModel: OrderViewModel, navController: NavHostController ) { viewModel.resetOrder() navController.popBackStack(CupcakeScreen.Start.name, false) }
AndroidLearning/compose-training-cupcake/app/src/main/java/com/example/cupcake/CupcakeScreen.kt
998002077
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.cupcake.data import com.example.cupcake.R object DataSource { val flavors = listOf( R.string.vanilla, R.string.chocolate, R.string.red_velvet, R.string.salted_caramel, R.string.coffee ) val quantityOptions = listOf( Pair(R.string.one_cupcake, 1), Pair(R.string.six_cupcakes, 6), Pair(R.string.twelve_cupcakes, 12) ) }
AndroidLearning/compose-training-cupcake/app/src/main/java/com/example/cupcake/data/DataSource.kt
4143548309
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.cupcake.data /** * Data class that represents the current UI state in terms of [quantity], [flavor], * [dateOptions], selected pickup [date] and [price] */ data class OrderUiState( /** Selected cupcake quantity (1, 6, 12) */ val quantity: Int = 0, /** Flavor of the cupcakes in the order (such as "Chocolate", "Vanilla", etc..) */ val flavor: String = "", /** Selected date for pickup (such as "Jan 1") */ val date: String = "", /** Total price for the order */ val price: String = "", /** Available pickup dates for the order*/ val pickupOptions: List<String> = listOf() )
AndroidLearning/compose-training-cupcake/app/src/main/java/com/example/cupcake/data/OrderUiState.kt
582577361
package com.sti.nalirescue import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.sti.nalirescue", appContext.packageName) } }
Nali-Rescue/app/src/androidTest/java/com/sti/nalirescue/ExampleInstrumentedTest.kt
722288897
package com.sti.nalirescue import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
Nali-Rescue/app/src/test/java/com/sti/nalirescue/ExampleUnitTest.kt
2567849556
package com.sti.nalirescue import android.app.AlertDialog import android.content.DialogInterface import android.content.Intent import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.sti.nalirescue.R class Settings : Fragment() { private lateinit var recyclerView: RecyclerView private lateinit var adapter: SettingsAdapter override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_settings, container, false) recyclerView = view.findViewById(R.id.recyclerViewSetting) val settingsList = listOf(SettingsItem("Logout")) // Add other items as needed val sessionManager = SessionManager(requireContext()) // assuming SessionManager takes a context parameter adapter = SettingsAdapter(settingsList) { item -> // Handle click action for each item if (item.title == "Logout") { showLogoutConfirmationDialog() } } recyclerView.adapter = adapter recyclerView.layoutManager = LinearLayoutManager(activity) return view } private fun showLogoutConfirmationDialog() { val builder = AlertDialog.Builder(requireContext()) builder.setTitle("Logout") builder.setMessage("Are you sure you want to log out?") builder.setPositiveButton("Yes") { _: DialogInterface, _: Int -> // User clicked Yes, perform logout val sessionManager = SessionManager(requireContext()) sessionManager.logoutUser() val intent = Intent(requireContext(), LoginActivity::class.java) startActivity(intent) requireActivity().finish() } builder.setNegativeButton("No") { dialog: DialogInterface, _: Int -> // User clicked No, dismiss the dialog dialog.dismiss() } val dialog = builder.create() dialog.show() } }
Nali-Rescue/app/src/main/java/com/sti/nalirescue/Settings.kt
2680993463
package com.sti.nalirescue import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.fragment.app.Fragment import com.sti.nalirescue.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) replaceFragment(Home()) binding.bottomNavigationView.setOnItemSelectedListener { when(it.itemId){ R.id.home -> replaceFragment(Home()) R.id.profile -> replaceFragment(Profile()) R.id.settings -> replaceFragment(Settings()) else ->{ } } true } } private fun replaceFragment(fragment : Fragment){ val fragmentManager = supportFragmentManager val fragmentTransaction = fragmentManager.beginTransaction() fragmentTransaction.replace(R.id.frame_layout,fragment) fragmentTransaction.commit() } }
Nali-Rescue/app/src/main/java/com/sti/nalirescue/MainActivity.kt
389204779
package com.sti.nalirescue import retrofit2.Call import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.Query interface ApiInterface { @FormUrlEncoded @POST("login") // Replace with your actual login endpoint fun login( @Field("email") email: String, @Field("password") password: String ): Call<ApiResponse> @FormUrlEncoded @POST("register") // Replace with your actual registration endpoint fun register( @Field("name") name: String, @Field("email") email: String, @Field("password") password: String, @Field("roleId") roleId: Int, // Make sure to add this field if needed @Field("mobile") mobile: String, @Field("isAdmin") isAdmin: Int, // Make sure to add this field if needed @Field("createdBy") createdBy: Int, // Make sure to add this field if needed @Field("createdDtm") createdDtm: String // Add the createdDtm field as a String ): Call<ApiResponse> @FormUrlEncoded @POST("registerdevice") // Replace with your actual registration endpoint fun device( @Field("device_id") device_id: String, @Field("user_id") user_id: String, ): Call<ApiResponse> @FormUrlEncoded @POST("information") // Replace with your actual registration endpoint fun information( @Field("user_id") user_id: String, @Field("emer_contact") emer_contact: String, @Field("contact_address") contact_address: String, @Field("city_muni") city_muni: String, @Field("blood_type") blood_type: String, @Field("contact_person") contact_person: String, // Make sure to add this field if needed @Field("medical_history") medical_history: String, @Field("verified") verified: Int, // Make sure to add this field if needed @Field("date_added") date_added: String // Add the createdDtm field as a String ): Call<ApiResponse> @FormUrlEncoded @POST("updatetask") // Replace with your actual registration endpoint fun updatetask( @Field("taskId") user_id: String, @Field("description")description:String, @Field("rescue_status") status: String ): Call<ApiResponse> // Add a new method for checking user information // @FormUrlEncoded @GET("listtask") fun check(@Query("rescue") rescue: String, @Query("city_muni") cityMuni: String): Call<ApiResponse> @POST("checkdevice") fun checkerdevice(@Query("user_id") userId: String): Call<ApiResponse> }
Nali-Rescue/app/src/main/java/com/sti/nalirescue/ApiInterface.kt
1098941433
package com.sti.nalirescue class SettingsItem(val title: String)
Nali-Rescue/app/src/main/java/com/sti/nalirescue/SettingsItem.kt
1996517398
package com.sti.nalirescue import android.app.Dialog import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.Window import android.view.WindowManager import android.widget.Button import android.widget.TextView class CustomDialog(context: Context, private val link: String) : Dialog(context) { private lateinit var titleTextView: TextView private lateinit var closeButton: Button private lateinit var openLinkButton: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) requestWindowFeature(Window.FEATURE_NO_TITLE) setContentView(R.layout.custom_dialog) // Set the window size val window = window window?.setLayout( WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT ) titleTextView = findViewById(R.id.dialogTitle) closeButton = findViewById(R.id.dialogButton) openLinkButton = findViewById(R.id.openLinkButton) titleTextView.text = "Custom Dialog Title" closeButton.setOnClickListener { dismiss() } openLinkButton.setOnClickListener { // Open the link here (e.g., using Intent to open a web page) openLink(link) } } private fun openLink(link: String) { // You need to implement the logic to open the link here // For example, you can use an Intent to open a web page val intent = Intent(Intent.ACTION_VIEW, Uri.parse(link)) context.startActivity(intent) } // You can add more methods or modify the behavior as needed fun setDialogTitle(title: String) { titleTextView.text = title } fun setDialogDetails(details: String) { val detailsTextView: TextView = findViewById(R.id.dialogDetails) detailsTextView.text = details } fun setDialogLocation(location: String) { val locationTextView: TextView = findViewById(R.id.dialogLocation) locationTextView.text = location } fun setDialogMessage(message: String) { val messageTextView: TextView = findViewById(R.id.dialogMessage) messageTextView.text = message } fun setDialogDate(nalidate: String) { val dateTextView: TextView = findViewById(R.id.dialogDate) dateTextView.text = nalidate } fun setOnCloseButtonClickListener(listener: () -> Unit) { closeButton.setOnClickListener { listener.invoke() dismiss() } } }
Nali-Rescue/app/src/main/java/com/sti/nalirescue/CustomDialog.kt
3658015873
package com.sti.nalirescue import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView class TaskAdapter(private val onItemClick: (Task) -> Unit) : RecyclerView.Adapter<TaskAdapter.TaskViewHolder>() { private var tasks: List<Task> = emptyList() fun setTasks(tasks: List<Task>) { this.tasks = tasks notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TaskViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.task_item_layout, parent, false) return TaskViewHolder(view) } override fun onBindViewHolder(holder: TaskViewHolder, position: Int) { val task = tasks[position] holder.bind(task) holder.itemView.setOnClickListener { onItemClick(task) } } override fun getItemCount(): Int { return tasks.size } fun getTasks(): List<Task> { return tasks } class TaskViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val titleTextView: TextView = itemView.findViewById(R.id.titleTextView) val descriptionTextView: TextView = itemView.findViewById(R.id.descriptionTextView) val dateTextView: TextView = itemView.findViewById(R.id.dateTextView) val naliTextView: TextView = itemView.findViewById(R.id.naliTextView) fun bind(task: Task) { titleTextView.text = task.taskTitle descriptionTextView.text = task.message dateTextView.text = task.createdDtm.toString() naliTextView.text = task.device_id.toUpperCase() } } }
Nali-Rescue/app/src/main/java/com/sti/nalirescue/TaskAdapter.kt
4110621646
package com.sti.nalirescue import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build import android.os.Bundle import android.os.Handler import android.os.Looper import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.core.app.NotificationCompat import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.sti.nalirescue.R import okhttp3.OkHttpClient import com.sti.nalirescue.CustomDialog import okhttp3.Request import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Call import retrofit2.Callback import retrofit2.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class Home : Fragment() { private val BASE_URL = "https://naliproject.xyz/api/" private lateinit var adapter: TaskAdapter private val CHANNEL_ID = "MyChannel" private val NOTIFICATION_ID = 1 var googleMapsNavigationLink ="" private val handler = Handler(Looper.getMainLooper()) private val fetchRunnable = object : Runnable { override fun run() { // Call the function to fetch data fetchData() // Schedule the next data fetch after a delay (e.g., 10 seconds) handler.postDelayed(this, 10 * 1000) // 10 seconds in milliseconds } } // Declare customOkHttpClient as a class-level property private val customOkHttpClient: OkHttpClient by lazy { val loggingInterceptor = HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger { override fun log(message: String) { Log.d("API Request", message) } }).apply { level = HttpLoggingInterceptor.Level.BODY } OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .build() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_home, container, false) startPeriodicDataFetch() val recyclerView: RecyclerView = view.findViewById(R.id.recyclerView) recyclerView.layoutManager = LinearLayoutManager(requireContext()) // Inside your onCreateView method where you set up the OkHttpClient val loggingInterceptor = HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger { override fun log(message: String) { // Log the message as desired, e.g., to Android Logcat // You can also write it to a file or use any other logging mechanism Log.d("API Request", message) } }).apply { level = HttpLoggingInterceptor.Level.BODY // Set the desired logging level } val okHttpClient = OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .build() // Create an instance of your Retrofit service interface with the custom OkHttpClient val apiInterface = Retrofit.Builder() .baseUrl("https://naliproject.xyz/api/") // Replace with your CodeIgniter API base URL .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClient) // Set the OkHttpClient with the custom logging interceptor .build() .create(ApiInterface::class.java) val sessionManager = SessionManager(view.context) val role = sessionManager.getRoleID() adapter = TaskAdapter { task -> onTaskItemClick(task) } recyclerView.adapter = adapter return view } private fun startPeriodicDataFetch() { // Start the initial data fetch fetchData() // Schedule the next data fetch after a delay (e.g., 10 seconds) handler.postDelayed(fetchRunnable, 10 * 1000) // 10 seconds in milliseconds } private fun fetchData() { Log.d("FetchData", "Fetching data.") val loggingInterceptor = HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger { override fun log(message: String) { Log.d("API Request", message) } }).apply { level = HttpLoggingInterceptor.Level.BODY } val okHttpClient = OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .build() // Create an instance of your Retrofit service interface with the custom OkHttpClient val apiInterface = Retrofit.Builder() .baseUrl("https://naliproject.xyz/api/") // Replace with your CodeIgniter API base URL .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClient) // Set the OkHttpClient with the custom logging interceptor .build() .create(ApiInterface::class.java) val sessionManager = SessionManager(requireContext()) val role = sessionManager.getRoleID() val assign = sessionManager.getAssignValue() showToast(assign.toString()) var emer_type = "" if (role == 13) { emer_type = "PNP" } else if (role == 14) { emer_type = "MEDICAL" }else if (role == 16){ emer_type = "RELATIVE" } val call = apiInterface.check(emer_type,assign) call.enqueue(object : Callback<ApiResponse> { override fun onResponse(call: Call<ApiResponse>, response: Response<ApiResponse>) { if (response.isSuccessful) { val apiResponse = response.body() Log.e("USERINFO", apiResponse.toString()) if (apiResponse != null) { if (apiResponse.status == true) { val apiTasks = apiResponse.tasks val tasks = apiTasks.map { Task( it.taskId.toInt(), it.taskTitle, it.device_id, it.emergency_type, it.location, it.link, it.message, it.description, it.type, it.status, it.createdDtm ) } val existingTasks = adapter.getTasks() // Check if there are new tasks val newTasks = tasks.filterNot { existingTasks.contains(it) } // Update the adapter with the new tasks adapter.setTasks(tasks) val firstDeviceId: String? = tasks.firstOrNull()?.device_id val firstTaskTItle: String? = tasks.firstOrNull()?.taskTitle val firstMessage: String? = tasks.firstOrNull()?.message val location_area : String? = tasks.firstOrNull()?.location val firstLocation: String? = tasks.firstOrNull()?.link // Check if firstLocation is not null and starts with the specified prefix if (!firstLocation.isNullOrBlank() && firstLocation.startsWith("https://www.google.com/maps?q=")) { // Trim the prefix val coordinates = firstLocation.removePrefix("https://www.google.com/maps?q=") googleMapsNavigationLink = "https://www.google.com/maps/dir/?api=1&destination=$coordinates" Log.e("GPS",googleMapsNavigationLink) } else { // Handle the case where the URL format is not as expected println("Invalid URL format or location is null/blank.") } val firstDate: String? = tasks.firstOrNull()?.createdDtm // Check if new tasks are added if (newTasks.isNotEmpty()) { Log.d("Notification", "New tasks added: ${newTasks.size}") // Notify user about new tasks // Replace with your actual link val customDialog = CustomDialog(requireContext(), googleMapsNavigationLink) customDialog.show() customDialog.setDialogTitle(firstDeviceId.toString().toUpperCase()) customDialog.setDialogDetails(firstTaskTItle.toString()) customDialog.setDialogLocation(location_area.toString()) customDialog.setDialogMessage(firstMessage.toString()) customDialog.setDialogDate(firstDate.toString()) } } else { showToast("API response indicates failure: ${apiResponse.message}") } } else { showToast("API response is null") } } else { showToast("Waiting for new Data") } } override fun onFailure(call: Call<ApiResponse>, t: Throwable) { // Handle failure here showToast("Failed to fetch data from the API") } }) } private fun showToast(message: String) { Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show() } private fun showNotification(nali : String) { Log.d("Notification", "Notification is being shown.") val notificationManager = requireContext().getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager // Create a Notification Channel (for Android Oreo and higher) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel( CHANNEL_ID, "My Channel", NotificationManager.IMPORTANCE_DEFAULT ) notificationManager.createNotificationChannel(channel) } // Create an Intent to launch the app when the notification is clicked val intent = Intent(requireContext(), MainActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP val pendingIntent = PendingIntent.getActivity( requireContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE // or FLAG_MUTABLE ) // Create a Notification val notification = NotificationCompat.Builder(requireContext(), CHANNEL_ID) .setSmallIcon(R.drawable.nali) .setContentTitle(nali) .setContentText("You have new tasks to review.") .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setContentIntent(pendingIntent) // Set the PendingIntent for the notification .setAutoCancel(true) // Automatically removes the notification when clicked .build() // Show the Notification notificationManager.notify(NOTIFICATION_ID, notification) } // Add the onDestroyView method to remove the callback when the fragment is destroyed override fun onDestroyView() { super.onDestroyView() // Remove the callback to prevent memory leaks handler.removeCallbacks(fetchRunnable) } private fun onTaskItemClick(task: Task) { // Open TaskDetailsActivity and pass task details val intent = Intent(requireContext(), TaskDetailsActivity::class.java) intent.putExtra("TASK_ID", task.taskId) intent.putExtra("TASK_TITLE", task.taskTitle) intent.putExtra("TASK_DESCRIPTION", task.message) intent.putExtra("TASK_LOCATION", task.location) intent.putExtra("TASK_DIRECTION",googleMapsNavigationLink) intent.putExtra("TASK_LINK",task.link) startActivity(intent) } }
Nali-Rescue/app/src/main/java/com/sti/nalirescue/Home.kt
3017622039
package com.sti.nalirescue import android.content.Context import android.content.SharedPreferences class SessionManager(context: Context) { private val PREF_NAME = "Rescuer" private val KEY_USERNAME = "username" private val KEY_PASSWORD = "password" private val KEY_USER_ID = "userid" private val KEY_ROLE_ID = "role_id" private val KEY_USER_NAME = "user_name" private val KEY_IS_LOGGED_IN = "isLoggedIn" private val KEY_ASSIGN = "assign" private val sharedPreferences: SharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE) fun createLoginSession( username: String, password: String, userid: Int, role_id: Int, user_name:String,assign:String) { val editor = sharedPreferences.edit() editor.putString(KEY_USERNAME, username) editor.putString(KEY_PASSWORD, password) editor.putInt(KEY_USER_ID, userid) editor.putInt(KEY_ROLE_ID, role_id) editor.putString(KEY_USER_NAME,user_name)// Store as an integer editor.putString(KEY_ASSIGN,assign)// Store as an integer editor.putBoolean(KEY_IS_LOGGED_IN, true) editor.apply() } fun checkLogin(): Boolean { return sharedPreferences.getBoolean(KEY_IS_LOGGED_IN, false) } fun getUserDetails(): HashMap<String, Any> { // Change the return type to Any val user = HashMap<String, Any>() // Change the value type to Any user[KEY_USERNAME] = sharedPreferences.getString(KEY_USERNAME, "") ?: "" user[KEY_PASSWORD] = sharedPreferences.getString(KEY_PASSWORD, "") ?: "" user[KEY_USER_NAME] = sharedPreferences.getString(KEY_USER_NAME,"")?:"" user[KEY_ASSIGN] = sharedPreferences.getString(KEY_ASSIGN,"")?:"" user[KEY_USER_ID] = sharedPreferences.getInt(KEY_USER_ID, 0) // Retrieve as an integer user[KEY_ROLE_ID] = sharedPreferences.getInt(KEY_ROLE_ID, 0) // Retrieve as an integer return user } fun logoutUser() { val editor = sharedPreferences.edit() editor.clear() editor.apply() } // Getter method for KEY_USERNAME fun getUsernameKey(): String { return KEY_USERNAME } fun getAssignValue(): String { return sharedPreferences.getString(KEY_ASSIGN, "") ?: "" } // Getter method for KEY_USERNAME fun getUser_nameKey(): String { return KEY_USER_NAME } // Getter method for KEY_USERNAME fun getUserID(): Int { return sharedPreferences.getInt(KEY_USER_ID, 0) } // Getter method for KEY_ROLE_ID fun getRoleID(): Int { return sharedPreferences.getInt(KEY_ROLE_ID, 0) } }
Nali-Rescue/app/src/main/java/com/sti/nalirescue/SessionManager.kt
2925645024
package com.sti.nalirescue import java.math.BigInteger import java.util.Date data class User( val userId: String, val roleId: Int, val name :String, val assign :String // Add other user properties here ) data class ApiResponse( val status: Boolean, val message: String, val device_data: List<DeviceData>, val tasks:List<TaskData>, val login: Boolean, val result: Boolean, val user: User // Define it as an object, not a string ) data class DeviceData( val user_id: String, val device_id: String ) data class TaskData( val taskId: BigInteger, val taskTitle: String, val device_id: String, val emergency_type: String, val location:String, val link:String, val message: String, val description: String, val type:String, val status:String, val city_muni:String, val date:Date, val createdDtm:String )
Nali-Rescue/app/src/main/java/com/sti/nalirescue/ApiReponse.kt
766535907
package com.sti.nalirescue import java.math.BigInteger import java.util.Date data class Task( val taskId: Int, val taskTitle: String, val device_id: String, val emergency_type: String, val location: String, val link: String, val message: String, val description: String?, val type: String?, val status: String?, val createdDtm: String? )
Nali-Rescue/app/src/main/java/com/sti/nalirescue/Task.kt
3747612099
// TaskDetailsActivity.kt package com.sti.nalirescue import android.content.Intent import android.net.Uri import android.os.Bundle import android.util.Log import android.widget.ArrayAdapter import android.widget.Button import android.widget.EditText import android.widget.Spinner import androidx.appcompat.app.AppCompatActivity import android.widget.TextView import android.widget.Toast import androidx.appcompat.widget.Toolbar import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Call import retrofit2.Callback import retrofit2.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.math.BigInteger class TaskDetailsActivity : AppCompatActivity() { private lateinit var rescueDetails: EditText override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_task_details) val toolbar: Toolbar = findViewById(R.id.toolbar) setSupportActionBar(toolbar) // Enable the back button in the toolbar supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowHomeEnabled(true) val taskId = intent.getIntExtra("TASK_ID", -1) val taskTitle = intent.getStringExtra("TASK_TITLE") val taskDescription = intent.getStringExtra("TASK_DESCRIPTION") val tasklocation_ = intent.getStringExtra("TASK_LOCATION") val taskDirection = intent.getStringExtra("TASK_DIRECTION") // Use these details to populate your TaskDetailsActivity UI val titleTextView: TextView = findViewById(R.id.titleTextView) val descriptionTextView: TextView = findViewById(R.id.descriptionTextView) val locationTextView: TextView = findViewById(R.id.locationTextView) val townTextView: TextView = findViewById(R.id.townTextView) val buttonDirection: Button = findViewById(R.id.respondButton) rescueDetails = findViewById(R.id.editRescueText) val sessionManager = SessionManager(this) val role = sessionManager.getRoleID() val device = sessionManager.getUserID() showToast(role.toString()) val buttonApply: Button = findViewById(R.id.applyButton) // Inside your onCreateView method where you set up the OkHttpClient val loggingInterceptor = HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger { override fun log(message: String) { // Log the message as desired, e.g., to Android Logcat // You can also write it to a file or use any other logging mechanism Log.d("API Request", message) } }).apply { level = HttpLoggingInterceptor.Level.BODY // Set the desired logging level } // Inside onCreateView method val okHttpClient = OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .build() // Create an instance of your Retrofit service interface with the custom OkHttpClient val apiInterface = Retrofit.Builder() .baseUrl("https://naliproject.xyz/api/") // Replace with your CodeIgniter API base URL .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClient) // Set the OkHttpClient with the custom logging interceptor .build() .create(ApiInterface::class.java) titleTextView.text = taskTitle descriptionTextView.text = taskDescription locationTextView.text = tasklocation_ buttonDirection.setOnClickListener { // Replace "https://www.example.com" with the actual URL you want to open val url = taskDirection Log.e("URL",url.toString()) // // // Create an Intent with ACTION_VIEW and the URI of the webpage val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) // Start the activity with the intent startActivity(intent) } val spinner: Spinner = findViewById(R.id.itemSpinner) // Define an array of items val items = arrayOf("RESPONDING", "CANCLED", "DONE") // Create an ArrayAdapter using the string array and a default spinner layout val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, items) // Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) // Apply the adapter to the spinner spinner.adapter = adapter buttonApply.setOnClickListener { // Validate descriptionRescue val rescueDets = rescueDetails.text.toString() val selectedResp:String = spinner.selectedItem.toString() showToast(rescueDets) val call = apiInterface.updatetask( taskId.toString(), rescueDets, selectedResp, ) Log.d("DEVICE", "Request URL: ${call.request().url}") // Enqueue the call to run asynchronously call.enqueue(object : Callback<ApiResponse> { override fun onResponse(call: Call<ApiResponse>, response: Response<ApiResponse>) { Log.e("API-UPDATE", response.toString()) if (response.code() == 201) { // 201 Created is typically returned for successful registration val apiResponse = response.body() if (apiResponse != null && apiResponse.status == true) { Log.e("API-UPDATE", apiResponse.toString()) // Registration was successful Toast.makeText(applicationContext, "${apiResponse.message}", Toast.LENGTH_SHORT).show() // Registration was successful, navigate to LoginActivity finish() } else { Log.e("API", apiResponse.toString()) } } else { // Registration request failed Toast.makeText(applicationContext, "Registration request 1 failed", Toast.LENGTH_SHORT).show() } } override fun onFailure(call: Call<ApiResponse>, t: Throwable) { // Registration request failed Toast.makeText(applicationContext, "Registration request failed.", Toast.LENGTH_SHORT).show() t.printStackTrace() } }) } } private fun showToast(message:String){ Toast.makeText(this, message ,Toast.LENGTH_SHORT).show() } // Handle the back button press override fun onSupportNavigateUp(): Boolean { onBackPressed() return true } }
Nali-Rescue/app/src/main/java/com/sti/nalirescue/TaskDetailsActivity.kt
1545788166
package com.sti.nalirescue import android.content.Intent import android.os.Bundle import android.util.Log import android.view.View import androidx.appcompat.app.AppCompatActivity import android.widget.Button import android.widget.EditText import android.widget.Toast import com.sti.nalirescue.MainActivity import com.sti.nalirescue.R import retrofit2.Call import retrofit2.Callback import retrofit2.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class LoginActivity : AppCompatActivity() { private val BASE_URL = "https://naliproject.xyz/api/" // Replace with your API base URL private lateinit var usernameEditText: EditText private lateinit var passwordEditText: EditText override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) // Initialize UI elements usernameEditText = findViewById(R.id.usernameEditText) passwordEditText = findViewById(R.id.passwordEditText) val loginButton = findViewById<Button>(R.id.loginButton) // Set up Retrofit val retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() val apiInterface = retrofit.create(ApiInterface::class.java) // Check if the user is already logged in val sessionManager = SessionManager(this) if (sessionManager.checkLogin()) { val roleIdCheck = sessionManager.getRoleID() // User is logged in, redirect to the HomeActivity or desired activity val intent = Intent(this@LoginActivity,MainActivity::class.java) startActivity(intent) finish() } //Handle register button click // Handle login button click loginButton.setOnClickListener { val username = usernameEditText.text.toString() val password = passwordEditText.text.toString() // Call the login API using Retrofit apiInterface.login(username, password).enqueue(object : Callback<ApiResponse> { override fun onResponse(call: Call<ApiResponse>, response: Response<ApiResponse>) { if (response.isSuccessful) { val apiResponse = response.body() Log.e("LOGIN",apiResponse.toString()) // Check if login is true if (apiResponse?.login == true) { val user = apiResponse?.user val iduser = user?.userId val iduserInt = iduser?.toIntOrNull() ?: 0 val assign = user?.assign val roleId = user?.roleId val user_name = user?.name // real username val roleIdInt = roleId ?: 0 val username = usernameEditText.text.toString() // email val password = passwordEditText.text.toString() if(roleIdInt == 13) { // Save user credentials and login status val sessionManager = SessionManager(this@LoginActivity) if (assign != null) { sessionManager.createLoginSession(username, password, iduserInt,roleIdInt,user_name.toString(),assign) } // User is logged in, redirect to the HomeActivity or desired activity val intent = Intent(this@LoginActivity, MainActivity::class.java) startActivity(intent) finish() }else if (roleIdInt == 14){ if (assign != null) { sessionManager.createLoginSession(username, password, iduserInt,roleIdInt,user_name.toString(),assign) } // User is logged in, redirect to the HomeActivity or desired activity val intent = Intent(this@LoginActivity, MainActivity::class.java) startActivity(intent) finish() }else if (roleIdInt == 16){ if (assign != null) { sessionManager.createLoginSession(username, password, iduserInt,roleIdInt,user_name.toString(),assign) } // User is logged in, redirect to the HomeActivity or desired activity val intent = Intent(this@LoginActivity, MainActivity::class.java) startActivity(intent) finish() } } else { // Handle the case where login is false val errorMessage = "Login failed. Email and password are required." showToast(errorMessage) } } else { // Handle API error and display the status code val statusCode = response.code() val errorMessage = "API Error. Status Code: $statusCode" showToast(errorMessage) } } override fun onFailure(call: Call<ApiResponse>, t: Throwable) { // Log the error message Log.e("NetworkError", "Error: ${t.message}", t) // Show an error message to the user showToast("Network error. Please try again.") } }) } } private fun showToast(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } }
Nali-Rescue/app/src/main/java/com/sti/nalirescue/LoginActivity.kt
2811086233
package com.sti.nalirescue import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView class SettingsAdapter(private val settingsList: List<SettingsItem>, private val onItemClick: (SettingsItem) -> Unit) : RecyclerView.Adapter<SettingsAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.settings_item_layout, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = settingsList[position] holder.bind(item) } override fun getItemCount(): Int { return settingsList.size } inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val textViewTitle: TextView = itemView.findViewById(R.id.textViewTitle) init { itemView.setOnClickListener { onItemClick.invoke(settingsList[adapterPosition]) } } fun bind(item: SettingsItem) { textViewTitle.text = item.title } } }
Nali-Rescue/app/src/main/java/com/sti/nalirescue/SettingsAdapter.kt
1558450007
package com.sti.nalirescue import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.sti.nalirescue.R // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [Profile.newInstance] factory method to * create an instance of this fragment. */ class Profile : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_profile, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment Profile. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = Profile().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
Nali-Rescue/app/src/main/java/com/sti/nalirescue/Profile.kt
3932059393
package com.example.challenge_rekamin_satu import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.challenge_rekamin_satu", appContext.packageName) } }
kalkulator_kotlin/app/src/androidTest/java/com/example/challenge_rekamin_satu/ExampleInstrumentedTest.kt
2305704444
package com.example.challenge_rekamin_satu import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
kalkulator_kotlin/app/src/test/java/com/example/challenge_rekamin_satu/ExampleUnitTest.kt
2868113574
package com.example.challenge_rekamin_satu import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.challenge_rekamin_satu.ui.theme.Orange @Composable fun Kalkulator( state: StateKalkulator, buttonSpacing: Dp= 8.dp, modifier: Modifier = Modifier, onAction: (ActionKalkulator) -> Unit ) { Box(modifier = modifier){ Column ( modifier = Modifier .fillMaxWidth() .align(Alignment.BottomCenter), verticalArrangement = Arrangement.spacedBy(buttonSpacing) ) { Text( text = state.number1 + (state.operation?.symbol?: "") + state.number2, textAlign = TextAlign.End, modifier = Modifier .fillMaxWidth() .padding(vertical = 32.dp), fontWeight = FontWeight.Light, fontSize = 80.sp, color = Color.White, maxLines = 2 ) Row ( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(buttonSpacing) ) { ButtonKalkulator ( symbol = "AC", modifier = Modifier .background(Color.LightGray) .aspectRatio(2f) .weight(2f), onClick = { onAction(ActionKalkulator.Clear) } ) ButtonKalkulator ( symbol = "Del", modifier = Modifier .background(Color.LightGray) .aspectRatio(1f) .weight(1f), onClick = { onAction(ActionKalkulator.Delete) } ) ButtonKalkulator ( symbol = "/", modifier = Modifier .background(Color.LightGray) .aspectRatio(1f) .weight(1f), onClick = { onAction(ActionKalkulator.Operation(OperationKalkulator.Divide)) } ) } Row ( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(buttonSpacing) ) { ButtonKalkulator ( symbol = "7", modifier = Modifier .background(Color.DarkGray) .aspectRatio(1f) .weight(1f), onClick = { onAction(ActionKalkulator.Number(7)) } ) ButtonKalkulator ( symbol = "8", modifier = Modifier .background(Color.DarkGray) .aspectRatio(1f) .weight(1f), onClick = { onAction(ActionKalkulator.Number(8)) } ) ButtonKalkulator ( symbol = "9", modifier = Modifier .background(Color.DarkGray) .aspectRatio(1f) .weight(1f), onClick = { onAction(ActionKalkulator.Number(9)) } ) ButtonKalkulator ( symbol = "x", modifier = Modifier .background(Orange) .aspectRatio(1f) .weight(1f), onClick = { onAction(ActionKalkulator.Operation(OperationKalkulator.Multiply)) } ) } Row ( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(buttonSpacing) ) { ButtonKalkulator ( symbol = "4", modifier = Modifier .background(Color.DarkGray) .aspectRatio(1f) .weight(1f), onClick = { onAction(ActionKalkulator.Number(4)) } ) ButtonKalkulator ( symbol = "5", modifier = Modifier .background(Color.DarkGray) .aspectRatio(1f) .weight(1f), onClick = { onAction(ActionKalkulator.Number(5)) } ) ButtonKalkulator ( symbol = "6", modifier = Modifier .background(Color.DarkGray) .aspectRatio(1f) .weight(1f), onClick = { onAction(ActionKalkulator.Number(6)) } ) ButtonKalkulator ( symbol = "-", modifier = Modifier .background(Orange) .aspectRatio(1f) .weight(1f), onClick = { onAction(ActionKalkulator.Operation(OperationKalkulator.Subtract)) } ) } Row ( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(buttonSpacing) ) { ButtonKalkulator ( symbol = "1", modifier = Modifier .background(Color.DarkGray) .aspectRatio(1f) .weight(1f), onClick = { onAction(ActionKalkulator.Number(1)) } ) ButtonKalkulator ( symbol = "2", modifier = Modifier .background(Color.DarkGray) .aspectRatio(1f) .weight(1f), onClick = { onAction(ActionKalkulator.Number(2)) } ) ButtonKalkulator ( symbol = "3", modifier = Modifier .background(Color.DarkGray) .aspectRatio(1f) .weight(1f), onClick = { onAction(ActionKalkulator.Number(3)) } ) ButtonKalkulator ( symbol = "+", modifier = Modifier .background(Orange) .aspectRatio(1f) .weight(1f), onClick = { onAction(ActionKalkulator.Operation(OperationKalkulator.Add)) } ) } Row ( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(buttonSpacing) ) { ButtonKalkulator ( symbol = "0", modifier = Modifier .background(Color.DarkGray) .aspectRatio(2f) .weight(2f), onClick = { onAction(ActionKalkulator.Number(0)) } ) ButtonKalkulator ( symbol = ".", modifier = Modifier .background(Color.DarkGray) .aspectRatio(1f) .weight(1f), onClick = { onAction(ActionKalkulator.Desimal) } ) ButtonKalkulator ( symbol = "=", modifier = Modifier .background(Orange) .aspectRatio(1f) .weight(1f), onClick = { onAction(ActionKalkulator.Kalkulator) } ) } } } }
kalkulator_kotlin/app/src/main/java/com/example/challenge_rekamin_satu/Kalkulator.kt
446071388
package com.example.challenge_rekamin_satu.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260) val MediumGray = Color(0xFF2E2E2E) val lightGray = Color(0xFF818181) val Orange = Color(0xFFFF9800)
kalkulator_kotlin/app/src/main/java/com/example/challenge_rekamin_satu/ui/theme/Color.kt
1843673336
package com.example.challenge_rekamin_satu.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun Challenge_rekamin_satuTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
kalkulator_kotlin/app/src/main/java/com/example/challenge_rekamin_satu/ui/theme/Theme.kt
1835132469
package com.example.challenge_rekamin_satu.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
kalkulator_kotlin/app/src/main/java/com/example/challenge_rekamin_satu/ui/theme/Type.kt
2994460186
package com.example.challenge_rekamin_satu data class StateKalkulator( val number1: String="", val number2: String="", val operation: OperationKalkulator? = null )
kalkulator_kotlin/app/src/main/java/com/example/challenge_rekamin_satu/StateKalkulator.kt
1285208825
package com.example.challenge_rekamin_satu import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.background import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import com.example.challenge_rekamin_satu.ui.theme.Challenge_rekamin_satuTheme import com.example.challenge_rekamin_satu.ui.theme.MediumGray class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Challenge_rekamin_satuTheme { val viewModel = viewModel<ViewModelKalkulator>() val state = viewModel.state val buttonSpacing = 8.dp Kalkulator( state = state, onAction = viewModel::onAction, buttonSpacing = buttonSpacing, modifier = Modifier .fillMaxSize() .background(MediumGray) .padding(16.dp) ) } } } }
kalkulator_kotlin/app/src/main/java/com/example/challenge_rekamin_satu/MainActivity.kt
445024437
package com.example.challenge_rekamin_satu import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel class ViewModelKalkulator: ViewModel() { var state by mutableStateOf(StateKalkulator()) private set fun onAction(action: ActionKalkulator){ when(action){ is ActionKalkulator.Number -> enterNumber(action.number) is ActionKalkulator.Desimal -> enterDecimal() is ActionKalkulator.Clear -> state = StateKalkulator() is ActionKalkulator.Operation -> enterOperation (action.operation) is ActionKalkulator.Kalkulator -> performKalkulation() is ActionKalkulator.Delete -> performDeletion() } } private fun performDeletion() { when { state.number2.isBlank() -> state = state.copy( number2 = state.number2.dropLast(1) ) state.operation != null -> state = state.copy( operation = null ) state.number1.isNotBlank() -> state = state.copy( number1 = state.number1.dropLast(1) ) } } private fun performKalkulation() { val number1 = state.number1.toDoubleOrNull() val number2 = state.number2.toDoubleOrNull() if (number1 != null && number2 != null){ val result = when(state.operation){ is OperationKalkulator.Add -> number1 + number2 is OperationKalkulator.Subtract -> number1 - number2 is OperationKalkulator.Multiply -> number1 * number2 is OperationKalkulator.Divide -> number1 / number2 null -> return } state =state.copy( number1 = result.toString().take(15), number2 = "", operation = null ) } } private fun enterOperation(operation: OperationKalkulator) { if(state.number1.isBlank()) { state = state.copy(operation = operation) } } private fun enterDecimal() { if (state.operation == null && !state.number1.contains(".") && state.number1.isNotBlank() ) { state = state.copy( number1 = state.number1 + "." ) return } if (!state.number2.contains(".") && state.number2.isNotBlank() ) { state = state.copy( number1 = state.number2 + "." ) } } private fun enterNumber(number: Int) { if (state.operation == null){ if (state.number1.length >= MAX_NUM_LENGTH){ return } state = state.copy( number1 = state.number1 + number ) return } if (state.number2.length >= MAX_NUM_LENGTH){ return } state = state.copy( number2 = state.number2 + number ) } companion object{ private const val MAX_NUM_LENGTH = 8 } }
kalkulator_kotlin/app/src/main/java/com/example/challenge_rekamin_satu/ViewModelKalkulator.kt
1334158847
package com.example.challenge_rekamin_satu sealed class ActionKalkulator { data class Number(val number : Int): ActionKalkulator() object Clear: ActionKalkulator() object Delete: ActionKalkulator() object Desimal: ActionKalkulator() object Kalkulator : ActionKalkulator() data class Operation(val operation: OperationKalkulator): ActionKalkulator() }
kalkulator_kotlin/app/src/main/java/com/example/challenge_rekamin_satu/ActionKalkulator.kt
983271589