path
stringlengths
4
297
contentHash
stringlengths
1
10
content
stringlengths
0
13M
AndroidLearning/compose-training-reply-app/app/src/main/java/com/example/reply/ui/ReplyHomeScreen.kt
108703493
/* * 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.reply.ui import android.app.Activity import androidx.compose.animation.AnimatedVisibility 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.fillMaxHeight 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.layout.width import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Drafts import androidx.compose.material.icons.filled.Inbox import androidx.compose.material.icons.filled.Report import androidx.compose.material.icons.filled.Send import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.NavigationBar import androidx.compose.material3.NavigationBarItem import androidx.compose.material3.NavigationDrawerItem import androidx.compose.material3.NavigationDrawerItemDefaults import androidx.compose.material3.NavigationRail import androidx.compose.material3.NavigationRailItem import androidx.compose.material3.PermanentDrawerSheet import androidx.compose.material3.PermanentNavigationDrawer 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.graphics.vector.ImageVector import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import com.example.reply.R import com.example.reply.data.Email import com.example.reply.data.MailboxType import com.example.reply.data.local.LocalAccountsDataProvider import com.example.reply.ui.utils.ReplyContentType import com.example.reply.ui.utils.ReplyNavigationType @Composable fun ReplyHomeScreen( navigationType: ReplyNavigationType, contentType: ReplyContentType, replyUiState: ReplyUiState, onTabPressed: (MailboxType) -> Unit, onEmailCardPressed: (Email) -> Unit, onDetailScreenBackPressed: () -> Unit, modifier: Modifier = Modifier ) { val navigationItemContentList = listOf( NavigationItemContent( mailboxType = MailboxType.Inbox, icon = Icons.Default.Inbox, text = stringResource(id = R.string.tab_inbox) ), NavigationItemContent( mailboxType = MailboxType.Sent, icon = Icons.Default.Send, text = stringResource(id = R.string.tab_sent) ), NavigationItemContent( mailboxType = MailboxType.Drafts, icon = Icons.Default.Drafts, text = stringResource(id = R.string.tab_drafts) ), NavigationItemContent( mailboxType = MailboxType.Spam, icon = Icons.Default.Report, text = stringResource(id = R.string.tab_spam) ) ) if (navigationType == ReplyNavigationType.PERMANENT_NAVIGATION_DRAWER) { val navigationDrawerContentDescription = stringResource(R.string.navigation_drawer) PermanentNavigationDrawer( modifier = Modifier.testTag(navigationDrawerContentDescription), drawerContent = { PermanentDrawerSheet( Modifier.width(dimensionResource(R.dimen.drawer_width)) ) { NavigationDrawerContent( selectedDestination = replyUiState.currentMailbox, onTabPressed = onTabPressed, navigationItemContentList = navigationItemContentList, modifier = Modifier .wrapContentWidth() .fillMaxHeight() .background(MaterialTheme.colorScheme.inverseOnSurface) .padding(dimensionResource(R.dimen.drawer_padding_content)) ) } }, ) { ReplyAppContent( contentType = contentType, navigationType = navigationType, replyUiState = replyUiState, onTabPressed = onTabPressed, onEmailCardPressed = onEmailCardPressed, navigationItemContentList = navigationItemContentList, modifier = modifier ) } } else { if (replyUiState.isShowingHomepage) { ReplyAppContent( contentType = contentType, navigationType = navigationType, replyUiState = replyUiState, onTabPressed = onTabPressed, onEmailCardPressed = onEmailCardPressed, navigationItemContentList = navigationItemContentList, modifier = modifier ) } else { ReplyDetailsScreen( replyUiState = replyUiState, onBackPressed = onDetailScreenBackPressed, modifier = modifier, true ) } } } @Composable private fun ReplyAppContent( navigationType: ReplyNavigationType, contentType: ReplyContentType, replyUiState: ReplyUiState, onTabPressed: ((MailboxType) -> Unit), onEmailCardPressed: (Email) -> Unit, navigationItemContentList: List<NavigationItemContent>, modifier: Modifier = Modifier, ) { val activity = LocalContext.current as Activity Box(modifier = modifier) { Row(modifier = Modifier.fillMaxSize()) { AnimatedVisibility(visible = navigationType == ReplyNavigationType.NAVIGATION_RAIL) { val navigationRailContentDescription = stringResource(R.string.navigation_rail) ReplyNavigationRail( currentTab = replyUiState.currentMailbox, onTabPressed = onTabPressed, navigationItemContentList = navigationItemContentList, modifier = Modifier .testTag(navigationRailContentDescription) ) } Column( modifier = Modifier .fillMaxSize() .background(MaterialTheme.colorScheme.inverseOnSurface) ) { if (contentType == ReplyContentType.LIST_AND_DETAIL) { ReplyListAndDetailContent( replyUiState = replyUiState, onEmailCardPressed = onEmailCardPressed, modifier = Modifier.weight(1f) ) } else { ReplyListOnlyContent( replyUiState = replyUiState, onEmailCardPressed = onEmailCardPressed, modifier = Modifier .weight(1f) .padding( horizontal = dimensionResource(R.dimen.email_list_only_horizontal_padding) ) ) } AnimatedVisibility( visible = navigationType == ReplyNavigationType.BOTTOM_NAVIGATION ) { val bottomNavigationDescription = stringResource(id = R.string.navigation_bottom) ReplyBottomNavigationBar( currentTab = replyUiState.currentMailbox, onTabPressed = onTabPressed, navigationItemContentList = navigationItemContentList, modifier = Modifier .fillMaxWidth() .testTag(bottomNavigationDescription) ) } } } } } @Composable private fun ReplyNavigationRail( currentTab: MailboxType, onTabPressed: ((MailboxType) -> Unit), navigationItemContentList: List<NavigationItemContent>, modifier: Modifier = Modifier ) { NavigationRail(modifier = modifier) { for (navItem in navigationItemContentList) { NavigationRailItem( selected = currentTab == navItem.mailboxType, onClick = { onTabPressed(navItem.mailboxType) }, icon = { Icon( imageVector = navItem.icon, contentDescription = navItem.text ) } ) } } } @Composable private fun ReplyBottomNavigationBar( currentTab: MailboxType, onTabPressed: ((MailboxType) -> Unit), navigationItemContentList: List<NavigationItemContent>, modifier: Modifier = Modifier ) { NavigationBar(modifier = modifier) { for (navItem in navigationItemContentList) { NavigationBarItem( selected = currentTab == navItem.mailboxType, onClick = { onTabPressed(navItem.mailboxType) }, icon = { Icon( imageVector = navItem.icon, contentDescription = navItem.text ) } ) } } } @Composable private fun NavigationDrawerContent( selectedDestination: MailboxType, onTabPressed: ((MailboxType) -> Unit), navigationItemContentList: List<NavigationItemContent>, modifier: Modifier = Modifier ) { Column(modifier = modifier) { NavigationDrawerHeader( modifier = Modifier .fillMaxWidth() .padding(dimensionResource(R.dimen.profile_image_padding)), ) for (navItem in navigationItemContentList) { NavigationDrawerItem( selected = selectedDestination == navItem.mailboxType, label = { Text( text = navItem.text, modifier = Modifier.padding(horizontal = dimensionResource(R.dimen.drawer_padding_header)) ) }, icon = { Icon( imageVector = navItem.icon, contentDescription = navItem.text ) }, colors = NavigationDrawerItemDefaults.colors( unselectedContainerColor = Color.Transparent ), onClick = { onTabPressed(navItem.mailboxType) } ) } } } @Composable private fun NavigationDrawerHeader( modifier: Modifier = Modifier ) { Row( modifier = modifier, horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { ReplyLogo(modifier = Modifier.size(dimensionResource(R.dimen.reply_logo_size))) ReplyProfileImage( drawableResource = LocalAccountsDataProvider.defaultAccount.avatar, description = stringResource(id = R.string.profile), modifier = Modifier .size(dimensionResource(R.dimen.profile_image_size)) ) } } private data class NavigationItemContent( val mailboxType: MailboxType, val icon: ImageVector, val text: String )
AndroidLearning/compose-training-reply-app/app/src/main/java/com/example/reply/ui/ReplyUiState.kt
1098534396
/* * 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.reply.ui import com.example.reply.data.Email import com.example.reply.data.MailboxType import com.example.reply.data.local.LocalEmailsDataProvider data class ReplyUiState( val mailboxes: Map<MailboxType, List<Email>> = emptyMap(), val currentMailbox: MailboxType = MailboxType.Inbox, val currentSelectedEmail: Email = LocalEmailsDataProvider.defaultEmail, val isShowingHomepage: Boolean = true ) { val currentMailboxEmails: List<Email> by lazy { mailboxes[currentMailbox]!! } }
AndroidLearning/compose-training-reply-app/app/src/main/java/com/example/reply/ui/theme/Color.kt
1408203468
/* * 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.reply.ui.theme import androidx.compose.ui.graphics.Color val md_theme_light_primary = Color(0xFF006879) val md_theme_light_onPrimary = Color(0xFFFFFFFF) val md_theme_light_primaryContainer = Color(0xFFA9EDFF) val md_theme_light_onPrimaryContainer = Color(0xFF001F26) val md_theme_light_secondary = Color(0xFF4B6268) val md_theme_light_onSecondary = Color(0xFFFFFFFF) val md_theme_light_secondaryContainer = Color(0xFFCEE7EE) val md_theme_light_onSecondaryContainer = Color(0xFF061F24) val md_theme_light_tertiary = Color(0xFF565D7E) val md_theme_light_onTertiary = Color(0xFFFFFFFF) val md_theme_light_tertiaryContainer = Color(0xFFDDE1FF) val md_theme_light_onTertiaryContainer = Color(0xFF121A37) 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(0xFFFBFCFD) val md_theme_light_onBackground = Color(0xFF191C1D) val md_theme_light_surface = Color(0xFFFBFCFD) val md_theme_light_onSurface = Color(0xFF191C1D) val md_theme_light_surfaceVariant = Color(0xFFDBE4E7) val md_theme_light_onSurfaceVariant = Color(0xFF3F484B) val md_theme_light_outline = Color(0xFF6F797B) val md_theme_light_inverseOnSurface = Color(0xFFEFF1F2) val md_theme_light_inverseSurface = Color(0xFF2E3132) val md_theme_light_inversePrimary = Color(0xFF54D7F3) val md_theme_light_surfaceTint = Color(0xFF006879) val md_theme_light_outlineVariant = Color(0xFFBFC8CB) val md_theme_light_scrim = Color(0xFF000000) val md_theme_dark_primary = Color(0xFF54D7F3) val md_theme_dark_onPrimary = Color(0xFF003640) val md_theme_dark_primaryContainer = Color(0xFF004E5B) val md_theme_dark_onPrimaryContainer = Color(0xFFA9EDFF) val md_theme_dark_secondary = Color(0xFFB2CBD2) val md_theme_dark_onSecondary = Color(0xFF1C343A) val md_theme_dark_secondaryContainer = Color(0xFF334A50) val md_theme_dark_onSecondaryContainer = Color(0xFFCEE7EE) val md_theme_dark_tertiary = Color(0xFFBEC5EB) val md_theme_dark_onTertiary = Color(0xFF282F4D) val md_theme_dark_tertiaryContainer = Color(0xFF3E4565) val md_theme_dark_onTertiaryContainer = Color(0xFFDDE1FF) 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(0xFF191C1D) val md_theme_dark_onBackground = Color(0xFFE1E3E4) val md_theme_dark_surface = Color(0xFF191C1D) val md_theme_dark_onSurface = Color(0xFFE1E3E4) val md_theme_dark_surfaceVariant = Color(0xFF3F484B) val md_theme_dark_onSurfaceVariant = Color(0xFFBFC8CB) val md_theme_dark_outline = Color(0xFF899295) val md_theme_dark_inverseOnSurface = Color(0xFF191C1D) val md_theme_dark_inverseSurface = Color(0xFFE1E3E4) val md_theme_dark_inversePrimary = Color(0xFF006879) val md_theme_dark_surfaceTint = Color(0xFF54D7F3) val md_theme_dark_outlineVariant = Color(0xFF3F484B) val md_theme_dark_scrim = Color(0xFF000000)
AndroidLearning/compose-training-reply-app/app/src/main/java/com/example/reply/ui/theme/Theme.kt
1794857538
/* * 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.reply.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.lightColorScheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme 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 ReplyTheme( darkTheme: Boolean = isSystemInDarkTheme(), 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-reply-app/app/src/main/java/com/example/reply/ui/theme/Type.kt
1019064958
/* * 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.reply.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 val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) )
AndroidLearning/compose-training-reply-app/app/src/main/java/com/example/reply/ui/ReplyDetailsScreen.kt
903602997
/* * 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.reply.ui import android.widget.Toast import androidx.activity.compose.BackHandler 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.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.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Icon import androidx.compose.material3.IconButton 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.platform.LocalContext import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import com.example.reply.R import com.example.reply.data.Email import com.example.reply.data.MailboxType @Composable fun ReplyDetailsScreen( replyUiState: ReplyUiState, onBackPressed: () -> Unit, modifier: Modifier = Modifier, isFullScreen: Boolean = false, ) { BackHandler { onBackPressed() } Box(modifier = modifier) { LazyColumn( modifier = Modifier .fillMaxSize() .background(color = MaterialTheme.colorScheme.inverseOnSurface) .padding(top = dimensionResource(R.dimen.detail_card_list_padding_top)) ) { item { if (isFullScreen) { ReplyDetailsScreenTopBar( onBackPressed, replyUiState, Modifier .fillMaxWidth() .padding(bottom = dimensionResource(R.dimen.detail_topbar_padding_bottom)) ) } ReplyEmailDetailsCard( email = replyUiState.currentSelectedEmail, mailboxType = replyUiState.currentMailbox, modifier = if (isFullScreen) { Modifier.padding(horizontal = dimensionResource(R.dimen.detail_card_outer_padding_horizontal)) } else { Modifier.padding(end = dimensionResource(R.dimen.detail_card_outer_padding_horizontal)) } ) } } } } @Composable private fun ReplyDetailsScreenTopBar( onBackButtonClicked: () -> Unit, replyUiState: ReplyUiState, modifier: Modifier = Modifier ) { Row( modifier = modifier, verticalAlignment = Alignment.CenterVertically, ) { IconButton( onClick = onBackButtonClicked, modifier = Modifier .padding(horizontal = dimensionResource(R.dimen.detail_topbar_back_button_padding_horizontal)) .background(MaterialTheme.colorScheme.surface, shape = CircleShape), ) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = stringResource(id = R.string.navigation_back) ) } Row( horizontalArrangement = Arrangement.Center, modifier = Modifier .fillMaxWidth() .padding(end = dimensionResource(R.dimen.detail_subject_padding_end)) ) { Text( text = stringResource(replyUiState.currentSelectedEmail.subject), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onSurfaceVariant ) } } } @Composable private fun ReplyEmailDetailsCard( email: Email, mailboxType: MailboxType, modifier: Modifier = Modifier, isFullScreen: Boolean = false ) { val context = LocalContext.current val displayToast = { text: String -> Toast.makeText(context, text, Toast.LENGTH_SHORT).show() } Card( modifier = modifier, colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface) ) { Column( modifier = Modifier .fillMaxWidth() .padding(dimensionResource(R.dimen.detail_card_inner_padding)) ) { DetailsScreenHeader( email, Modifier.fillMaxWidth() ) if (isFullScreen) { Spacer(modifier = Modifier.height(dimensionResource(id = R.dimen.detail_content_padding_top))) } else { Text( text = stringResource(email.subject), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.outline, modifier = Modifier.padding( top = dimensionResource(R.dimen.detail_content_padding_top), bottom = dimensionResource(R.dimen.detail_expanded_subject_body_spacing) ), ) } Text( text = stringResource(email.body), style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurfaceVariant, ) DetailsScreenButtonBar(mailboxType, displayToast) } } } @Composable private fun DetailsScreenButtonBar( mailboxType: MailboxType, displayToast: (String) -> Unit, modifier: Modifier = Modifier ) { Box(modifier = modifier) { when (mailboxType) { MailboxType.Drafts -> ActionButton( text = stringResource(id = R.string.continue_composing), onButtonClicked = displayToast ) MailboxType.Spam -> Row( modifier = Modifier .fillMaxWidth() .padding( vertical = dimensionResource(R.dimen.detail_button_bar_padding_vertical) ), horizontalArrangement = Arrangement.spacedBy( dimensionResource(R.dimen.detail_button_bar_item_spacing) ), ) { ActionButton( text = stringResource(id = R.string.move_to_inbox), onButtonClicked = displayToast, modifier = Modifier.weight(1f) ) ActionButton( text = stringResource(id = R.string.delete), onButtonClicked = displayToast, containIrreversibleAction = true, modifier = Modifier.weight(1f) ) } MailboxType.Sent, MailboxType.Inbox -> Row( modifier = Modifier .fillMaxWidth() .padding( vertical = dimensionResource(R.dimen.detail_button_bar_padding_vertical) ), horizontalArrangement = Arrangement.spacedBy( dimensionResource(R.dimen.detail_button_bar_item_spacing) ), ) { ActionButton( text = stringResource(id = R.string.reply), onButtonClicked = displayToast, modifier = Modifier.weight(1f) ) ActionButton( text = stringResource(id = R.string.reply_all), onButtonClicked = displayToast, modifier = Modifier.weight(1f) ) } } } } @Composable private fun DetailsScreenHeader(email: Email, modifier: Modifier = Modifier) { Row(modifier = modifier) { ReplyProfileImage( drawableResource = email.sender.avatar, description = stringResource(email.sender.firstName) + " " + stringResource(email.sender.lastName), modifier = Modifier.size( dimensionResource(R.dimen.email_header_profile_size) ) ) Column( modifier = Modifier .weight(1f) .padding( horizontal = dimensionResource(R.dimen.email_header_content_padding_horizontal), vertical = dimensionResource(R.dimen.email_header_content_padding_vertical) ), verticalArrangement = Arrangement.Center ) { Text( text = stringResource(email.sender.firstName), style = MaterialTheme.typography.labelMedium ) Text( text = stringResource(email.createdAt), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.outline ) } } } @Composable private fun ActionButton( text: String, onButtonClicked: (String) -> Unit, modifier: Modifier = Modifier, containIrreversibleAction: Boolean = false, ) { Box(modifier = modifier) { Button( onClick = { onButtonClicked(text) }, modifier = Modifier .fillMaxWidth() .padding(vertical = dimensionResource(R.dimen.detail_action_button_padding_vertical)), colors = ButtonDefaults.buttonColors( containerColor = if (containIrreversibleAction) { MaterialTheme.colorScheme.onErrorContainer } else { MaterialTheme.colorScheme.primaryContainer } ) ) { Text( text = text, color = if (containIrreversibleAction) { MaterialTheme.colorScheme.onError } else { MaterialTheme.colorScheme.onSurfaceVariant } ) } } }
AndroidLearning/compose-training-reply-app/app/src/main/java/com/example/reply/MainActivity.kt
287309706
/* * 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.reply import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.material3.Surface import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass import androidx.compose.material3.windowsizeclass.calculateWindowSizeClass import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview import com.example.reply.ui.ReplyApp import com.example.reply.ui.theme.ReplyTheme class MainActivity : ComponentActivity() { @OptIn(ExperimentalMaterial3WindowSizeClassApi::class) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ReplyTheme { Surface { val windowSize = calculateWindowSizeClass(this) ReplyApp( windowSize = windowSize.widthSizeClass, ) } } } } } @Preview(showBackground = true) @Composable fun ReplyAppCompactPreview() { ReplyTheme { Surface { ReplyApp( windowSize = WindowWidthSizeClass.Compact, ) } } } @Preview(showBackground = true, widthDp = 700) @Composable fun ReplyAppMediumPreview() { ReplyTheme { Surface { ReplyApp(windowSize = WindowWidthSizeClass.Medium) } } } @Preview(showBackground = true, widthDp = 1000) @Composable fun ReplyAppExpandedPreview() { ReplyTheme { Surface { ReplyApp(windowSize = WindowWidthSizeClass.Expanded) } } }
AndroidLearning/compose-training-reply-app/app/src/main/java/com/example/reply/data/Email.kt
594865175
/* * 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.reply.data import androidx.annotation.StringRes /** * A simple data class to represent an Email */ data class Email( /** Unique ID of the email **/ val id: Long, /** Sender of the email **/ val sender: Account, /** Recipient(s) of the email **/ val recipients: List<Account> = emptyList(), /** Title of the email **/ @StringRes val subject: Int = -1, /** Content of the email **/ @StringRes val body: Int = -1, /** Which mailbox it is in **/ var mailbox: MailboxType = MailboxType.Inbox, /** * Relative duration in which it was created. (e.g. 20 mins ago) * It should be calculated from relative time in the future. * For now it's hard coded to a [String] value. */ @StringRes var createdAt: Int = -1 )
AndroidLearning/compose-training-reply-app/app/src/main/java/com/example/reply/data/Account.kt
2950049882
/* * 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.reply.data import androidx.annotation.DrawableRes import androidx.annotation.StringRes /** * A class which represents an account */ data class Account( /** Unique ID of a user **/ val id: Long, /** User's first name **/ @StringRes val firstName: Int, /** User's last name **/ @StringRes val lastName: Int, /** User's email address **/ @StringRes val email: Int, /** User's avatar image resource id **/ @DrawableRes val avatar: Int )
AndroidLearning/compose-training-reply-app/app/src/main/java/com/example/reply/data/local/LocalEmailsDataProvider.kt
166451387
/* * 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.reply.data.local import com.example.reply.R import com.example.reply.data.Email import com.example.reply.data.MailboxType /** * A static data store of [Email]s. */ object LocalEmailsDataProvider { val allEmails = listOf( Email( id = 0L, sender = LocalAccountsDataProvider.getContactAccountById(9L), recipients = listOf(LocalAccountsDataProvider.defaultAccount), subject = R.string.email_0_subject, body = R.string.email_0_body, createdAt = R.string.email_0_time, ), Email( id = 1L, sender = LocalAccountsDataProvider.getContactAccountById(6L), recipients = listOf(LocalAccountsDataProvider.defaultAccount), subject = R.string.email_1_subject, body = R.string.email_1_body, createdAt = R.string.email_1_time, ), Email( 2L, LocalAccountsDataProvider.getContactAccountById(5L), listOf(LocalAccountsDataProvider.defaultAccount), subject = R.string.email_2_subject, body = R.string.email_2_body, createdAt = R.string.email_2_time, ), Email( 3L, LocalAccountsDataProvider.getContactAccountById(8L), listOf(LocalAccountsDataProvider.defaultAccount), subject = R.string.email_3_subject, body = R.string.email_3_body, createdAt = R.string.email_3_time, mailbox = MailboxType.Sent, ), Email( id = 4L, sender = LocalAccountsDataProvider.getContactAccountById(11L), subject = R.string.email_4_subject, body = R.string.email_4_body, createdAt = R.string.email_4_time, ), Email( id = 5L, sender = LocalAccountsDataProvider.getContactAccountById(13L), recipients = listOf(LocalAccountsDataProvider.defaultAccount), subject = R.string.email_5_subject, body = R.string.email_5_body, createdAt = R.string.email_5_time, ), Email( id = 6L, sender = LocalAccountsDataProvider.getContactAccountById(10L), recipients = listOf(LocalAccountsDataProvider.defaultAccount), subject = R.string.email_6_subject, body = R.string.email_6_body, createdAt = R.string.email_6_time, mailbox = MailboxType.Sent, ), Email( id = 7L, sender = LocalAccountsDataProvider.getContactAccountById(9L), recipients = listOf(LocalAccountsDataProvider.defaultAccount), subject = R.string.email_7_subject, body = R.string.email_7_body, createdAt = R.string.email_7_time, ), Email( id = 8L, sender = LocalAccountsDataProvider.getContactAccountById(13L), recipients = listOf(LocalAccountsDataProvider.defaultAccount), subject = R.string.email_8_subject, body = R.string.email_8_body, createdAt = R.string.email_8_time, ), Email( id = 9L, sender = LocalAccountsDataProvider.getContactAccountById(10L), recipients = listOf(LocalAccountsDataProvider.defaultAccount), subject = R.string.email_9_subject, body = R.string.email_9_body, createdAt = R.string.email_9_time, mailbox = MailboxType.Drafts, ), Email( id = 10L, sender = LocalAccountsDataProvider.getContactAccountById(5L), recipients = listOf(LocalAccountsDataProvider.defaultAccount), subject = R.string.email_10_subject, body = R.string.email_10_body, createdAt = R.string.email_10_time, ), Email( id = 11L, sender = LocalAccountsDataProvider.getContactAccountById(5L), recipients = listOf(LocalAccountsDataProvider.defaultAccount), subject = R.string.email_11_subject, body = R.string.email_11_body, createdAt = R.string.email_11_time, mailbox = MailboxType.Spam, ) ) /** * Get an [Email] with the given [id]. */ fun get(id: Long): Email? { return allEmails.firstOrNull { it.id == id } } val defaultEmail = Email( id = -1, sender = LocalAccountsDataProvider.defaultAccount, ) }
AndroidLearning/compose-training-reply-app/app/src/main/java/com/example/reply/data/local/LocalAccountsDataProvider.kt
1129306024
/* * 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.reply.data.local import com.example.reply.R import com.example.reply.data.Account /** * An static data store of [Account]s. This includes both [Account]s owned by the current user and * all [Account]s of the current user's contacts. */ object LocalAccountsDataProvider { val defaultAccount = Account(-1, -1, -1, -1, R.drawable.avatar_1) val userAccount = Account( id = 1, firstName = R.string.account_1_first_name, lastName = R.string.account_1_last_name, email = R.string.account_1_email, avatar = R.drawable.avatar_10 ) private val allUserContactAccounts = listOf( Account( id = 4L, firstName = R.string.account_4_first_name, lastName = R.string.account_4_last_name, email = R.string.account_4_email, avatar = R.drawable.avatar_1 ), Account( id = 5L, firstName = R.string.account_5_first_name, lastName = R.string.account_5_last_name, email = R.string.account_5_email, avatar = R.drawable.avatar_3 ), Account( id = 6L, firstName = R.string.account_6_first_name, lastName = R.string.account_6_last_name, email = R.string.account_6_email, avatar = R.drawable.avatar_5 ), Account( id = 7L, firstName = R.string.account_7_first_name, lastName = R.string.account_7_last_name, email = R.string.account_7_email, avatar = R.drawable.avatar_0 ), Account( id = 8L, firstName = R.string.account_8_first_name, lastName = R.string.account_8_last_name, email = R.string.account_8_email, avatar = R.drawable.avatar_7 ), Account( id = 9L, firstName = R.string.account_9_first_name, lastName = R.string.account_9_last_name, email = R.string.account_9_email, avatar = R.drawable.avatar_express ), Account( id = 10L, firstName = R.string.account_10_first_name, lastName = R.string.account_10_last_name, email = R.string.account_10_email, avatar = R.drawable.avatar_2 ), Account( id = 11L, firstName = R.string.account_11_first_name, lastName = R.string.account_11_last_name, email = R.string.account_11_email, avatar = R.drawable.avatar_8 ), Account( id = 12L, firstName = R.string.account_12_first_name, lastName = R.string.account_12_last_name, email = R.string.account_12_email, avatar = R.drawable.avatar_6 ), Account( id = 13L, firstName = R.string.account_13_first_name, lastName = R.string.account_13_last_name, email = R.string.account_13_email, avatar = R.drawable.avatar_4 ) ) /** * Get the contact of the current user with the given [accountId]. */ fun getContactAccountById(accountId: Long): Account { return allUserContactAccounts.firstOrNull { it.id == accountId } ?: allUserContactAccounts.first() } }
AndroidLearning/compose-training-reply-app/app/src/main/java/com/example/reply/data/MailboxType.kt
3242064677
/* * 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.reply.data /** * An enum class to define different types of email folders or categories. */ enum class MailboxType { Inbox, Drafts, Sent, Spam }
AndroidLearning/compose-training-race-tracker/app/src/test/java/com/example/racetracker/RaceParticipantTest.kt
2677409220
/* * 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.racetracker import com.example.racetracker.ui.RaceParticipant import junit.framework.TestCase.assertEquals import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.launch import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest import org.junit.Test class RaceParticipantTest { private val raceParticipant = RaceParticipant( name = "Test", maxProgress = 100, progressDelayMillis = 500L, initialProgress = 0, progressIncrement = 1 ) @OptIn(ExperimentalCoroutinesApi::class) @Test fun raceParticipant_RaceStarted_ProgressUpdated() = runTest { val expectedProgress = 1 launch { raceParticipant.run() } advanceTimeBy(raceParticipant.progressDelayMillis) runCurrent() assertEquals(expectedProgress, raceParticipant.currentProgress) } @OptIn(ExperimentalCoroutinesApi::class) @Test fun raceParticipant_RaceFinished_ProgressUpdated() = runTest { launch { raceParticipant.run() } advanceTimeBy(raceParticipant.maxProgress * raceParticipant.progressDelayMillis) runCurrent() assertEquals(100, raceParticipant.currentProgress) } }
AndroidLearning/compose-training-race-tracker/app/src/main/java/com/example/racetracker/ui/RaceParticipant.kt
2784880172
/* * 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.racetracker.ui import android.util.Log import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import kotlinx.coroutines.CancellationException import kotlinx.coroutines.delay /** * This class represents a state holder for race participant. */ class RaceParticipant( val name: String, val maxProgress: Int = 100, val progressDelayMillis: Long = 500L, private val progressIncrement: Int = 1, private val initialProgress: Int = 0 ) { init { require(maxProgress > 0) { "maxProgress=$maxProgress; must be > 0" } require(progressIncrement > 0) { "progressIncrement=$progressIncrement; must be > 0" } } /** * Indicates the race participant's current progress */ var currentProgress by mutableStateOf(initialProgress) private set suspend fun run() { try { while (currentProgress < maxProgress) { delay(progressDelayMillis) currentProgress += progressIncrement } }catch (e:CancellationException){ Log.e("RaceParticipant", "$name: ${e.message}") throw e // Always re-throw CancellationException. } } /** * Regardless of the value of [initialProgress] the reset function will reset the * [currentProgress] to 0 */ fun reset() { currentProgress = 0 } } /** * The Linear progress indicator expects progress value in the range of 0-1. This property * calculate the progress factor to satisfy the indicator requirements. */ val RaceParticipant.progressFactor: Float get() = currentProgress / maxProgress.toFloat()
AndroidLearning/compose-training-race-tracker/app/src/main/java/com/example/racetracker/ui/RaceTrackerApp.kt
1729704674
/* * 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.racetracker.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.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.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Button import androidx.compose.material3.Icon import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember 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.draw.clip 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 com.example.racetracker.R import com.example.racetracker.ui.theme.RaceTrackerTheme import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch @Composable fun RaceTrackerApp() { /** * Note: To survive the configuration changes such as screen rotation, [rememberSaveable] should * be used with custom Saver object. But to keep the example simple, and keep focus on * Coroutines that implementation detail is stripped out. */ val playerOne = remember { RaceParticipant(name = "Player 1", progressIncrement = 1) } val playerTwo = remember { RaceParticipant(name = "Player 2", progressIncrement = 2) } var raceInProgress by remember { mutableStateOf(false) } if (raceInProgress) { LaunchedEffect(playerOne, playerTwo) { coroutineScope { launch { playerOne.run() } launch { playerTwo.run() } } raceInProgress = false } } RaceTrackerScreen( playerOne = playerOne, playerTwo = playerTwo, isRunning = raceInProgress, onRunStateChange = { raceInProgress = it }, modifier = Modifier .statusBarsPadding() .fillMaxSize() .verticalScroll(rememberScrollState()) .safeDrawingPadding() .padding(horizontal = dimensionResource(R.dimen.padding_medium)), ) } @Composable private fun RaceTrackerScreen( playerOne: RaceParticipant, playerTwo: RaceParticipant, isRunning: Boolean, onRunStateChange: (Boolean) -> Unit, modifier: Modifier = Modifier ) { Column( modifier = modifier, verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = stringResource(R.string.run_a_race), style = MaterialTheme.typography.headlineSmall, ) Column( modifier = Modifier .fillMaxSize() .padding(dimensionResource(R.dimen.padding_medium)), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { Icon( painter = painterResource(R.drawable.ic_walk), contentDescription = null, modifier = Modifier.padding(dimensionResource(R.dimen.padding_medium)), ) StatusIndicator( participantName = playerOne.name, currentProgress = playerOne.currentProgress, maxProgress = stringResource( R.string.progress_percentage, playerOne.maxProgress ), progressFactor = playerOne.progressFactor, modifier = Modifier.fillMaxWidth() ) Spacer(modifier = Modifier.size(dimensionResource(R.dimen.padding_large))) StatusIndicator( participantName = playerTwo.name, currentProgress = playerTwo.currentProgress, maxProgress = stringResource( R.string.progress_percentage, playerTwo.maxProgress ), progressFactor = playerTwo.progressFactor, modifier = Modifier.fillMaxWidth(), ) Spacer(modifier = Modifier.size(dimensionResource(R.dimen.padding_large))) RaceControls( isRunning = isRunning, onRunStateChange = onRunStateChange, onReset = { playerOne.reset() playerTwo.reset() onRunStateChange(false) }, modifier = Modifier.fillMaxWidth(), ) } } } @Composable private fun StatusIndicator( participantName: String, currentProgress: Int, maxProgress: String, progressFactor: Float, modifier: Modifier = Modifier ) { Row( modifier = modifier ) { Text( text = participantName, modifier = Modifier.padding(end = dimensionResource(R.dimen.padding_small)) ) Column( verticalArrangement = Arrangement.spacedBy(dimensionResource(R.dimen.padding_small)) ) { LinearProgressIndicator( progress = progressFactor, modifier = Modifier .fillMaxWidth() .height(dimensionResource(R.dimen.progress_indicator_height)) .clip(RoundedCornerShape(dimensionResource(R.dimen.progress_indicator_corner_radius))) ) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = stringResource(R.string.progress_percentage, currentProgress), textAlign = TextAlign.Start, modifier = Modifier.weight(1f) ) Text( text = maxProgress, textAlign = TextAlign.End, modifier = Modifier.weight(1f) ) } } } } @Composable private fun RaceControls( onRunStateChange: (Boolean) -> Unit, onReset: () -> Unit, modifier: Modifier = Modifier, isRunning: Boolean = true, ) { Column( modifier = modifier.padding(top = dimensionResource(R.dimen.padding_medium)), verticalArrangement = Arrangement.spacedBy(dimensionResource(R.dimen.padding_medium)) ) { Button( onClick = { onRunStateChange(!isRunning) }, modifier = Modifier.fillMaxWidth(), ) { Text(if (isRunning) stringResource(R.string.pause) else stringResource(R.string.start)) } OutlinedButton( onClick = onReset, modifier = Modifier.fillMaxWidth(), ) { Text(stringResource(R.string.reset)) } } } @Preview(showBackground = true) @Composable fun RaceTrackerAppPreview() { RaceTrackerTheme { RaceTrackerApp() } }
AndroidLearning/compose-training-race-tracker/app/src/main/java/com/example/racetracker/ui/theme/Color.kt
1023910610
/* * 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.racetracker.ui.theme import androidx.compose.ui.graphics.Color val md_theme_light_primary = Color(0xFFA23F00) val md_theme_light_onPrimary = Color(0xFFFFFFFF) val md_theme_light_primaryContainer = Color(0xFFFFDBCC) val md_theme_light_onPrimaryContainer = Color(0xFF351000) val md_theme_light_secondary = Color(0xFF76574A) val md_theme_light_onSecondary = Color(0xFFFFFFFF) val md_theme_light_secondaryContainer = Color(0xFFFFDBCC) val md_theme_light_onSecondaryContainer = Color(0xFF2C160C) val md_theme_light_tertiary = Color(0xFF665F31) val md_theme_light_onTertiary = Color(0xFFFFFFFF) val md_theme_light_tertiaryContainer = Color(0xFFEEE4A9) val md_theme_light_onTertiaryContainer = Color(0xFF201C00) 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(0xFF201A18) val md_theme_light_surface = Color(0xFFFFFBFF) val md_theme_light_onSurface = Color(0xFF201A18) val md_theme_light_surfaceVariant = Color(0xFFF4DED5) val md_theme_light_onSurfaceVariant = Color(0xFF52443D) val md_theme_light_outline = Color(0xFF85736C) val md_theme_light_inverseOnSurface = Color(0xFFFBEEE9) val md_theme_light_inverseSurface = Color(0xFF362F2C) val md_theme_light_inversePrimary = Color(0xFFFFB695) val md_theme_light_shadow = Color(0xFF000000) val md_theme_light_surfaceTint = Color(0xFFA23F00) val md_theme_light_outlineVariant = Color(0xFFD8C2BA) val md_theme_light_scrim = Color(0xFF000000) val md_theme_dark_primary = Color(0xFFFFB695) val md_theme_dark_onPrimary = Color(0xFF571F00) val md_theme_dark_primaryContainer = Color(0xFF7B2F00) val md_theme_dark_onPrimaryContainer = Color(0xFFFFDBCC) val md_theme_dark_secondary = Color(0xFFE6BEAD) val md_theme_dark_onSecondary = Color(0xFF442A1F) val md_theme_dark_secondaryContainer = Color(0xFF5D4034) val md_theme_dark_onSecondaryContainer = Color(0xFFFFDBCC) val md_theme_dark_tertiary = Color(0xFFD1C88F) val md_theme_dark_onTertiary = Color(0xFF363106) val md_theme_dark_tertiaryContainer = Color(0xFF4E471B) val md_theme_dark_onTertiaryContainer = Color(0xFFEEE4A9) 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(0xFF201A18) val md_theme_dark_onBackground = Color(0xFFEDE0DB) val md_theme_dark_surface = Color(0xFF201A18) val md_theme_dark_onSurface = Color(0xFFEDE0DB) val md_theme_dark_surfaceVariant = Color(0xFF52443D) val md_theme_dark_onSurfaceVariant = Color(0xFFD8C2BA) val md_theme_dark_outline = Color(0xFFA08D85) val md_theme_dark_inverseOnSurface = Color(0xFF201A18) val md_theme_dark_inverseSurface = Color(0xFFEDE0DB) val md_theme_dark_inversePrimary = Color(0xFFA23F00) val md_theme_dark_shadow = Color(0xFF000000) val md_theme_dark_surfaceTint = Color(0xFFFFB695) val md_theme_dark_outlineVariant = Color(0xFF52443D) val md_theme_dark_scrim = Color(0xFF000000)
AndroidLearning/compose-training-race-tracker/app/src/main/java/com/example/racetracker/ui/theme/Theme.kt
191274217
/* * 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.racetracker.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 RaceTrackerTheme( 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 } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
AndroidLearning/compose-training-race-tracker/app/src/main/java/com/example/racetracker/ui/theme/Type.kt
1481981863
/* * 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.racetracker.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-race-tracker/app/src/main/java/com/example/racetracker/MainActivity.kt
2135823089
/* * 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.racetracker 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.Surface import androidx.compose.ui.Modifier import com.example.racetracker.ui.RaceTrackerApp import com.example.racetracker.ui.theme.RaceTrackerTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { enableEdgeToEdge() super.onCreate(savedInstanceState) setContent { RaceTrackerTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), ) { RaceTrackerApp() } } } } }
AndroidLearning/kotlin-sql-basics-app-compose/app/src/androidTest/java/com/example/sqldemo/ExampleInstrumentedTest.kt
3981903659
package com.example.sqldemo 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.sqldemo", appContext.packageName) } }
AndroidLearning/kotlin-sql-basics-app-compose/app/src/test/java/com/example/sqldemo/ExampleUnitTest.kt
855005314
package com.example.sqldemo 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/kotlin-sql-basics-app-compose/app/src/main/java/com/example/sqldemo/ui/theme/Shape.kt
1293172813
/* * Copyright (C) 2022 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.sqldemo.ui.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( small = RoundedCornerShape(4.dp), medium = RoundedCornerShape(4.dp), large = RoundedCornerShape(0.dp) )
AndroidLearning/kotlin-sql-basics-app-compose/app/src/main/java/com/example/sqldemo/ui/theme/Color.kt
3159954763
/* * Copyright (C) 2022 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.sqldemo.ui.theme import androidx.compose.ui.graphics.Color val Purple200 = Color(0xFFBB86FC) val Purple500 = Color(0xFF6200EE) val Purple700 = Color(0xFF3700B3) val Teal200 = Color(0xFF03DAC5)
AndroidLearning/kotlin-sql-basics-app-compose/app/src/main/java/com/example/sqldemo/ui/theme/Theme.kt
3486927495
/* * Copyright (C) 2022 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.sqldemo.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable private val DarkColorPalette = darkColors( primary = Purple200, primaryVariant = Purple700, secondary = Teal200 ) private val LightColorPalette = lightColors( primary = Purple500, primaryVariant = Purple700, secondary = Teal200 /* Other default colors to override background = Color.White, surface = Color.White, onPrimary = Color.White, onSecondary = Color.Black, onBackground = Color.Black, onSurface = Color.Black, */ ) @Composable fun SQLDemoTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) { val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } MaterialTheme( colors = colors, typography = Typography, shapes = Shapes, content = content ) }
AndroidLearning/kotlin-sql-basics-app-compose/app/src/main/java/com/example/sqldemo/ui/theme/Type.kt
3124629473
/* * Copyright (C) 2022 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.sqldemo.ui.theme import androidx.compose.material.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( body1 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp ) /* Other default text styles to override button = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.W500, fontSize = 14.sp ), caption = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 12.sp ) */ )
AndroidLearning/kotlin-sql-basics-app-compose/app/src/main/java/com/example/sqldemo/Email.kt
115594876
/* * Copyright (C) 2022 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.sqldemo import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "email") data class Email( @PrimaryKey(autoGenerate = true) val id: Int, @ColumnInfo(name = "subject") val subject: String, @ColumnInfo(name = "sender") val sender: String, @ColumnInfo(name = "folder") val folder: String, @ColumnInfo(name = "starred") val starred: Boolean, @ColumnInfo(name = "read") val read: Boolean, @ColumnInfo(name = "received") val received: Int )
AndroidLearning/kotlin-sql-basics-app-compose/app/src/main/java/com/example/sqldemo/MainActivity.kt
507678969
/* * Copyright (C) 2022 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.sqldemo import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import com.example.sqldemo.ui.theme.SQLDemoTheme import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) GlobalScope.launch { AppDatabase.getDatabase(applicationContext).emailDao().getAll() } setContent { SQLDemoTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background ) { Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { Text("The database is ready!") } } } } } }
AndroidLearning/kotlin-sql-basics-app-compose/app/src/main/java/com/example/sqldemo/EmailDao.kt
1829968925
/* * Copyright (C) 2022 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.sqldemo import androidx.room.Dao import androidx.room.Query @Dao interface EmailDao { @Query("SELECT * FROM email") suspend fun getAll(): List<Email> }
AndroidLearning/kotlin-sql-basics-app-compose/app/src/main/java/com/example/sqldemo/AppDatabase.kt
1223530751
/* * Copyright (C) 2022 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.sqldemo import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase @Database(entities = arrayOf(Email::class), version = 1) abstract class AppDatabase: RoomDatabase() { abstract fun emailDao(): EmailDao companion object { @Volatile private var INSTANCE: AppDatabase? = null fun getDatabase( context: Context ): AppDatabase { return INSTANCE ?: synchronized(this) { val instance = Room.databaseBuilder( context, AppDatabase::class.java, "app_database" ) .createFromAsset("database/Email.db") .build() INSTANCE = instance instance } } } }
AndroidLearning/appcomponents/app/src/androidTest/java/com/suhas/activity/ExampleInstrumentedTest.kt
3408039639
package com.suhas.activity 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.suhas.activity", appContext.packageName) } }
AndroidLearning/appcomponents/app/src/test/java/com/suhas/activity/ExampleUnitTest.kt
168364524
package com.suhas.activity 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/appcomponents/app/src/main/java/com/suhas/activity/providers/MyProvider.kt
3484757417
package com.suhas.activity.providers import android.content.ContentProvider import android.content.ContentUris import android.content.ContentValues import android.content.Context import android.content.UriMatcher import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteException import android.database.sqlite.SQLiteOpenHelper import android.database.sqlite.SQLiteQueryBuilder import android.net.Uri class MyProvider : ContentProvider() { private var db: SQLiteDatabase? = null companion object { //Defining authority so that other application can access it const val PROVIDER_NAME = "com.suhas.activity.provider" //defining content URI const val URL = "content://$PROVIDER_NAME/users" //prasing the content uri val CONTENT_URI = Uri.parse(URL) const val id = "id" const val name = "name" const val uriCode = 1 var uriMatcher: UriMatcher? = null private val values: HashMap<String, String>? = null //declaring name of Database const val DATABASE_NAME = "UserDB" //declaring table name of the database const val TABLE_NAME = "Users" //declaring database version const val DB_VERSION = 1 //sql Query to create table const val CREATE_DB_TABLE = ("CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY AUTOINCREMENT," + "name TEXT NOT NULL);") init { //to match the content uri //every time user access table undercontent provider uriMatcher = UriMatcher(UriMatcher.NO_MATCH) //to access whole table uriMatcher!!.addURI( PROVIDER_NAME, "users", uriCode ) //to acess a particular row //of the table uriMatcher!!.addURI( PROVIDER_NAME, "users/*", uriCode ) } } override fun getType(p0: Uri): String? { return when (uriMatcher!!.match(p0)) { uriCode -> "vnd.android.cursor.dir/users" else -> throw IllegalArgumentException("Unsupported URI: $p0") } } override fun onCreate(): Boolean { val context = context val dbHelper = DatabseHelper(context) db = dbHelper.writableDatabase return db != null } override fun query( p0: Uri, p1: Array<out String>?, p2: String?, p3: Array<out String>?, p4: String? ): Cursor? { var sortOrder = p4 val qb = SQLiteQueryBuilder() qb.tables = TABLE_NAME when (uriMatcher!!.match(p0)) { uriCode -> qb.projectionMap = values else -> throw IllegalArgumentException("UNKNOWN URI $p0") } if (sortOrder == null || sortOrder === "") { sortOrder = id } val c = qb.query(db, p1, p2, p3, null, null, sortOrder) c.setNotificationUri(context!!.contentResolver, p0) return c } override fun insert(p0: Uri, p1: ContentValues?): Uri? { val rowID = db!!.insert(TABLE_NAME, "", p1) if (rowID > 0) { val uri = ContentUris.withAppendedId(CONTENT_URI, rowID) context!!.contentResolver.notifyChange(uri, null) return uri } else throw SQLiteException("Filed to add a record into $p0") } override fun delete(p0: Uri, p1: String?, p2: Array<out String>?): Int { var count = 0 count = when (uriMatcher!!.match(p0)) { uriCode -> db!!.delete(TABLE_NAME, p1, p2) else -> throw IllegalArgumentException("UNKNOWN URI $p0") } context!!.contentResolver.notifyChange(p0, null) return count } override fun update(p0: Uri, p1: ContentValues?, p2: String?, p3: Array<out String>?): Int { var count = 0 count = when (uriMatcher!!.match(p0)) { uriCode -> db!!.update(TABLE_NAME, p1, p2, p3) else -> throw IllegalArgumentException("UNKNOWN URI $p0") } context!!.contentResolver.notifyChange(p0, null) return count } //createing the object of database //to perform query private class DatabseHelper(context: Context?) : SQLiteOpenHelper(context, DATABASE_NAME, null, DB_VERSION) { override fun onCreate(db: SQLiteDatabase) { db.execSQL(CREATE_DB_TABLE) } override fun onUpgrade( db: SQLiteDatabase, oldversion: Int, newVersion: Int ) { //Sql query to drop a table //having similar name db.execSQL("DROP TABLE IF EXISTS $TABLE_NAME") } } }
AndroidLearning/appcomponents/app/src/main/java/com/suhas/activity/Main.kt
1381935830
package com.suhas.activity import android.annotation.SuppressLint import android.content.Intent import android.os.Bundle import android.widget.Button import androidx.appcompat.app.AppCompatActivity import com.suhas.activity.activites.BroadcastReciverExample import com.suhas.activity.activites.ContentResolverExample import com.suhas.activity.activites.LifeCycleActivity import com.suhas.activity.activites.ProviderExample import com.suhas.activity.activites.ServiceExample class Main : AppCompatActivity() { private lateinit var serviceExample: Button private lateinit var activityExample: Button private lateinit var reciverExample: Button private lateinit var providerExmple: Button private lateinit var resolverExmple: Button @SuppressLint("MissingInflatedId") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) serviceExample = findViewById(R.id.service_example) activityExample = findViewById(R.id.activity_example) reciverExample = findViewById(R.id.broadcast_receivers_example) providerExmple = findViewById(R.id.content_providers_example) resolverExmple = findViewById(R.id.content_resolver_example) resolverExmple.setOnClickListener { startActivity(Intent(this@Main, ContentResolverExample::class.java)) } serviceExample.setOnClickListener { startActivity(Intent(this@Main, ServiceExample::class.java)) } activityExample.setOnClickListener { startActivity(Intent(this@Main, LifeCycleActivity::class.java)) } reciverExample.setOnClickListener { startActivity( Intent( this@Main, BroadcastReciverExample::class.java ) ) } providerExmple.setOnClickListener { startActivity(Intent(this@Main, ProviderExample::class.java)) } } }
AndroidLearning/appcomponents/app/src/main/java/com/suhas/activity/activites/ContentResolverExample.kt
867738960
package com.suhas.activity.activites import android.annotation.SuppressLint import android.net.Uri import android.os.Bundle import android.view.View import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.suhas.activity.R class ContentResolverExample : AppCompatActivity() { val uri = Uri.parse("content://com.suhas.activity.provider/users") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_c_reslover) } @SuppressLint("Range") fun onClickShowDetails() { val resultView = findViewById<View>(R.id.res) as TextView val cursor = contentResolver.query( uri, null, null, null, null ) if (cursor!!.moveToFirst()) { val strBuild = StringBuilder() while (!cursor.isAfterLast) { strBuild.append( """${cursor.getString(cursor.getColumnIndex("id"))}-${ cursor.getString( cursor.getColumnIndex( "name" ) ) } """.trimIndent() ) cursor.moveToNext() } resultView.text = strBuild } else { resultView.text = "No Data Found!" } cursor.close() } }
AndroidLearning/appcomponents/app/src/main/java/com/suhas/activity/activites/LifeCycleActivity.kt
464305884
package com.suhas.activity.activites import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.suhas.activity.R /* This Activity Demonstrate Activity LifeCycle and State Changes */ class LifeCycleActivity : AppCompatActivity() { private val tag = "MainActivity" //onCreate() //This is the first callback and called when the activity is first created. override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_lifecycle_activity) Log.i(tag, ":-onCreate()") Show("onCreate()") } // onStart() // This callback is called when the activity becomes visible to the user. override fun onStart() { super.onStart() Log.i(tag, ":-onStart()") Show("onStart()") } //onPause() //The paused activity does not receive user input and cannot execute any code and called when the current activity is being paused and the previous activity is being resumed. override fun onPause() { super.onPause() Log.i(tag, ":-onPause()") Show("onPause()") } //onResume() //This is called when the user starts interacting with the application. override fun onResume() { super.onResume() Log.i(tag, ":-onResume()") Show("onResume()") } //onStop() //This callback is called when the activity is no longer visible. override fun onStop() { super.onStop() Log.i(tag, ":-onStop()") Show("onStop()") } //onDestroy() //This callback is called before the activity is destroyed by the system. override fun onDestroy() { super.onDestroy() Log.i(tag, ":-onDestroy()") Show("onDestroy()") } //onRestart() //This callback is called when the activity restarts after stopping it. override fun onRestart() { super.onRestart() Log.i(tag, ":-onRestart() ") Show("onRestart()") } fun Show(msg: String) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show() } }
AndroidLearning/appcomponents/app/src/main/java/com/suhas/activity/activites/ProviderExample.kt
2052852695
package com.suhas.activity.activites import android.annotation.SuppressLint import android.content.ContentValues import android.content.Context import android.net.Uri import android.os.Bundle import android.view.MotionEvent import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.EditText import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.suhas.activity.R import com.suhas.activity.providers.MyProvider import java.lang.StringBuilder class ProviderExample : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_c_provider) } override fun onTouchEvent(event: MotionEvent?): Boolean { val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(currentFocus!!.windowToken, 0) return super.onTouchEvent(event) } fun onClickAddDetails(view: View?) { val values = ContentValues() values.put( MyProvider.name, (findViewById<View>(R.id.textName) as EditText).text.toString() ) contentResolver.insert(MyProvider.CONTENT_URI, values) Toast.makeText(baseContext, "New Record Inserted", Toast.LENGTH_LONG).show() } @SuppressLint("Range") fun onClickShowDetails(view: View?) { val resultView = findViewById<View>(R.id.res) as TextView val cursor = contentResolver.query( Uri.parse("content://${MyProvider.PROVIDER_NAME}/users"), null, null, null, null ) if(cursor!!.moveToFirst()){ val strBuild=StringBuilder() while (!cursor.isAfterLast){ strBuild.append("""${cursor.getString(cursor.getColumnIndex("id"))}-${cursor.getString(cursor.getColumnIndex("name"))}""".trimIndent()) cursor.moveToNext() } resultView.text=strBuild }else{ resultView.text="No Records Found" } cursor.close() } }
AndroidLearning/appcomponents/app/src/main/java/com/suhas/activity/activites/ServiceExample.kt
1614313999
package com.suhas.activity.activites import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.Bundle import android.os.IBinder import android.widget.Button import androidx.appcompat.app.AppCompatActivity import com.suhas.activity.R import com.suhas.activity.services.MyService class ServiceExample : AppCompatActivity() { private var myBoundService: MyService? = null private val serviceConnection = object : ServiceConnection { override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) { myBoundService = (p1 as MyService.MyServiceBinder).getService() } override fun onServiceDisconnected(p0: ComponentName?) { myBoundService = null } } private lateinit var start: Button private lateinit var stop: Button private lateinit var bind: Button private lateinit var unBind: Button private lateinit var reBind: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_lifecycle_service) start = findViewById(R.id.start_service) stop = findViewById(R.id.stop_service) bind = findViewById(R.id.bind_service) unBind = findViewById(R.id.unbind_service) reBind = findViewById(R.id.rebind_service) val i = Intent(baseContext, MyService::class.java) start.setOnClickListener { startService(i) } stop.setOnClickListener { stopService(i) } bind.setOnClickListener { bindService(i, serviceConnection, Context.BIND_AUTO_CREATE) } unBind.setOnClickListener { unbindService(serviceConnection) } reBind.setOnClickListener { bindService(i, serviceConnection, BIND_AUTO_CREATE) } } }
AndroidLearning/appcomponents/app/src/main/java/com/suhas/activity/activites/BroadcastReciverExample.kt
3103392116
package com.suhas.activity.activites import android.content.Intent import android.content.IntentFilter import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.suhas.activity.R import com.suhas.activity.broadcast.MyReceiver class BroadcastReciverExample : AppCompatActivity() { private val reciver: MyReceiver = MyReceiver() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_reciver_example) val intentFilter = IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED) registerReceiver(reciver, intentFilter) } }
AndroidLearning/appcomponents/app/src/main/java/com/suhas/activity/broadcast/MyReceiver.kt
1950349079
package com.suhas.activity.broadcast import android.annotation.SuppressLint import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.widget.Toast class MyReceiver : BroadcastReceiver() { @SuppressLint("UnsafeProtectedBroadcastReceiver") override fun onReceive(p0: Context?, p1: Intent?) { val isAirplaneModeEnabled = p1?.getBooleanExtra("EXTRA_AIRPLANE_MODE", false) if ((isAirplaneModeEnabled != null) && isAirplaneModeEnabled) { Toast.makeText(p0,"Airplane Mode ON",Toast.LENGTH_SHORT).show() } else { Toast.makeText(p0,"Airplane Mode Off",Toast.LENGTH_SHORT).show() } } }
AndroidLearning/appcomponents/app/src/main/java/com/suhas/activity/services/MyService.kt
3150789938
package com.suhas.activity.services import android.app.Service import android.content.Intent import android.os.Binder import android.os.IBinder import android.widget.Toast class MyService : Service() { private val binder = MyServiceBinder() inner class MyServiceBinder : Binder() { fun getService(): MyService { return this@MyService } } override fun onCreate() { super.onCreate() Toast.makeText(this, "Service OnCreate.....", Toast.LENGTH_SHORT).show() } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { Toast.makeText(this, "Service Started.....", Toast.LENGTH_SHORT).show() return START_STICKY } override fun onDestroy() { Toast.makeText(this, "Service Destroy.....", Toast.LENGTH_SHORT).show() super.onDestroy() } override fun onBind(p0: Intent?): IBinder { Toast.makeText(this, "Service Bind.....", Toast.LENGTH_SHORT).show() return binder } override fun onRebind(intent: Intent?) { Toast.makeText(this, "Service ReBind.....", Toast.LENGTH_SHORT).show() super.onRebind(intent) } override fun onUnbind(intent: Intent?): Boolean { Toast.makeText(this, "Service UnBind.....", Toast.LENGTH_SHORT).show() return super.onUnbind(intent) } }
AndroidLearning/compose-training-woof/app/src/main/java/com/example/woof/ui/theme/Shape.kt
3742047819
/* * 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.ui.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( small = RoundedCornerShape(50.dp), medium = RoundedCornerShape(bottomStart = 16.dp, topEnd = 16.dp) )
AndroidLearning/compose-training-woof/app/src/main/java/com/example/woof/ui/theme/Color.kt
4222553654
package com.example.woof.ui.theme import androidx.compose.ui.graphics.Color val md_theme_light_primary = Color(0xFF006C4C) val md_theme_light_onPrimary = Color(0xFFFFFFFF) val md_theme_light_primaryContainer = Color(0xFF89F8C7) val md_theme_light_onPrimaryContainer = Color(0xFF002114) val md_theme_light_secondary = Color(0xFF4D6357) val md_theme_light_onSecondary = Color(0xFFFFFFFF) val md_theme_light_secondaryContainer = Color(0xFFCFE9D9) val md_theme_light_onSecondaryContainer = Color(0xFF092016) val md_theme_light_tertiary = Color(0xFF3D6373) val md_theme_light_onTertiary = Color(0xFFFFFFFF) val md_theme_light_tertiaryContainer = Color(0xFFC1E8FB) val md_theme_light_onTertiaryContainer = Color(0xFF001F29) 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(0xFFFBFDF9) val md_theme_light_onBackground = Color(0xFF191C1A) val md_theme_light_surface = Color(0xFFFBFDF9) val md_theme_light_onSurface = Color(0xFF191C1A) val md_theme_light_surfaceVariant = Color(0xFFDBE5DD) val md_theme_light_onSurfaceVariant = Color(0xFF404943) val md_theme_light_outline = Color(0xFF707973) val md_theme_light_inverseOnSurface = Color(0xFFEFF1ED) val md_theme_light_inverseSurface = Color(0xFF2E312F) val md_theme_light_inversePrimary = Color(0xFF6CDBAC) val md_theme_light_shadow = Color(0xFF000000) val md_theme_light_surfaceTint = Color(0xFF006C4C) val md_theme_light_outlineVariant = Color(0xFFBFC9C2) val md_theme_light_scrim = Color(0xFF000000) val md_theme_dark_primary = Color(0xFF6CDBAC) val md_theme_dark_onPrimary = Color(0xFF003826) val md_theme_dark_primaryContainer = Color(0xFF005138) val md_theme_dark_onPrimaryContainer = Color(0xFF89F8C7) val md_theme_dark_secondary = Color(0xFFB3CCBE) val md_theme_dark_onSecondary = Color(0xFF1F352A) val md_theme_dark_secondaryContainer = Color(0xFF354B40) val md_theme_dark_onSecondaryContainer = Color(0xFFCFE9D9) val md_theme_dark_tertiary = Color(0xFFA5CCDF) val md_theme_dark_onTertiary = Color(0xFF073543) val md_theme_dark_tertiaryContainer = Color(0xFF244C5B) val md_theme_dark_onTertiaryContainer = Color(0xFFC1E8FB) 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(0xFF191C1A) val md_theme_dark_onBackground = Color(0xFFE1E3DF) val md_theme_dark_surface = Color(0xFF191C1A) val md_theme_dark_onSurface = Color(0xFFE1E3DF) val md_theme_dark_surfaceVariant = Color(0xFF404943) val md_theme_dark_onSurfaceVariant = Color(0xFFBFC9C2) val md_theme_dark_outline = Color(0xFF8A938C) val md_theme_dark_inverseOnSurface = Color(0xFF191C1A) val md_theme_dark_inverseSurface = Color(0xFFE1E3DF) val md_theme_dark_inversePrimary = Color(0xFF006C4C) val md_theme_dark_shadow = Color(0xFF000000) val md_theme_dark_surfaceTint = Color(0xFF6CDBAC) val md_theme_dark_outlineVariant = Color(0xFF404943) val md_theme_dark_scrim = Color(0xFF000000)
AndroidLearning/compose-training-woof/app/src/main/java/com/example/woof/ui/theme/Theme.kt
2883482149
package com.example.woof.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 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 WoofTheme( 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 -> DarkColors else -> LightColors } val view = LocalView.current if (!view.isInEditMode) { SideEffect { setUpEdgeToEdge(view, darkTheme) } } MaterialTheme( colorScheme = colorScheme, shapes = Shapes, 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-woof/app/src/main/java/com/example/woof/ui/theme/Type.kt
3618564123
/* * 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.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp import com.example.woof.R val AbrilFatface = FontFamily( Font(R.font.abril_fatface_regular) ) val Montserrat = FontFamily( Font(R.font.montserrat_regular), Font(R.font.montserrat_bold, FontWeight.Bold) ) // Set of Material typography styles to start with val Typography = Typography( displayLarge = TextStyle( fontFamily = AbrilFatface, fontWeight = FontWeight.Normal, fontSize = 36.sp ), displayMedium = TextStyle( fontFamily = Montserrat, fontWeight = FontWeight.Bold, fontSize = 20.sp ), labelSmall = TextStyle( fontFamily = Montserrat, fontWeight = FontWeight.Bold, fontSize = 14.sp ), bodyLarge = TextStyle( fontFamily = Montserrat, fontWeight = FontWeight.Normal, fontSize = 14.sp ) )
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 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/data/Dog.kt
762462049
/* * 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-tip-calculator/app/src/androidTest/java/com/example/tiptime/TipUITest.kt
1232698491
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/test/java/com/example/tiptime/TipCalculatorTest.kt
1361900309
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/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 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/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 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/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.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/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.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-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 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/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 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/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 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/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.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/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.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/MainActivity.kt
4115886254
/* * 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/utils/WindowStateUtils.kt
3200165300
/* * 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/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.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/data/LocalSportsDataProvider.kt
2306095776
/* * 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-dessert-clicker/app/src/main/java/com/example/dessertclicker/ui/DessertViewModel.kt
440035031
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/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 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/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.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/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 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/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.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/data/Datasource.kt
841859431
/* * 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/DessertUiState.kt
298218059
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-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 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/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.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/MainActivity.kt
2608752274
/* * 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/model/Affirmation.kt
3956691913
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/data/Datasource.kt
2201905252
/* * 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/Amphibians/app/src/androidTest/java/com/example/amphibians/ExampleInstrumentedTest.kt
1395659388
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/test/java/com/example/amphibians/ExampleUnitTest.kt
2527638740
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/main/java/com/example/amphibians/ui/AmphibiansApp.kt
3578102173
@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/screens/HomeScreen.kt
3670253677
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/AmphibiansViewModel.kt
1363501137
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/theme/Color.kt
2271846463
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/Theme.kt
2562056878
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/Type.kt
1584967977
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/App.kt
2361729860
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/MainActivity.kt
3658878883
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/network/AmphibiansApiService.kt
1782404853
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/AmphibianPhoto.kt
3656920497
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/data/AppContainer.kt
59383402
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/AmphibiansDataRepository.kt
3082947266
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/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.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/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.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/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.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/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.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/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 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/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 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/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 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/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.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/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.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/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.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/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.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/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 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/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 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) }