diff --git a/AnimationCodelab/.gitignore b/AnimationCodelab/.gitignore new file mode 100644 index 0000000..10cfdbf --- /dev/null +++ b/AnimationCodelab/.gitignore @@ -0,0 +1,10 @@ +*.iml +.gradle +/local.properties +/.idea +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties diff --git a/AnimationCodelab/CONTRIBUTING.md b/AnimationCodelab/CONTRIBUTING.md new file mode 100644 index 0000000..bb70059 --- /dev/null +++ b/AnimationCodelab/CONTRIBUTING.md @@ -0,0 +1,28 @@ +# How to Contribute + +We'd love to accept your patches and contributions to this project. There are +just a few small guidelines you need to follow. + +## Contributor License Agreement + +Contributions to this project must be accompanied by a Contributor License +Agreement. You (or your employer) retain the copyright to your contribution, +this simply gives us permission to use and redistribute your contributions as +part of the project. Head over to to see +your current agreements on file or to sign a new one. + +You generally only need to submit a CLA once, so if you've already submitted one +(even if it was for a different project), you probably don't need to do it +again. + +## Code reviews + +All submissions, including submissions by project members, require review. We +use GitHub pull requests for this purpose. Consult +[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more +information on using pull requests. + +## Community Guidelines + +This project follows [Google's Open Source Community +Guidelines](https://opensource.google.com/conduct/). diff --git a/AnimationCodelab/LICENSE b/AnimationCodelab/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/AnimationCodelab/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/AnimationCodelab/README.md b/AnimationCodelab/README.md new file mode 100644 index 0000000..90cea07 --- /dev/null +++ b/AnimationCodelab/README.md @@ -0,0 +1,29 @@ +# Compose Animation Codelab + +This folder contains the source code for the +[Compose Animation](https://developer.android.com/codelabs/android-compose-animation) +codelab. + +In this codelab, you will learn how to use some Animation APIs in Jetpack Compose. + +## Screenshot + +![Screenshot](screenshots/app.png) + +## License + +``` +Copyright 2021 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. +``` diff --git a/AnimationCodelab/build.gradle b/AnimationCodelab/build.gradle new file mode 100644 index 0000000..3362ba0 --- /dev/null +++ b/AnimationCodelab/build.gradle @@ -0,0 +1,33 @@ +/* + * Copyright 2021 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. + */ + +buildscript { + repositories { + google() + mavenCentral() + } + dependencies { + classpath 'com.android.tools.build:gradle:7.3.1' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.20" + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} diff --git a/AnimationCodelab/finished/.gitignore b/AnimationCodelab/finished/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/AnimationCodelab/finished/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/AnimationCodelab/finished/build.gradle b/AnimationCodelab/finished/build.gradle new file mode 100644 index 0000000..d8b257e --- /dev/null +++ b/AnimationCodelab/finished/build.gradle @@ -0,0 +1,66 @@ +/* + * Copyright 2021 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. + */ + +plugins { + id 'com.android.application' + id 'kotlin-android' +} + +android { + compileSdkVersion 33 + defaultConfig { + applicationId 'com.example.android.codelab.animation' + minSdkVersion 21 + targetSdkVersion 33 + versionCode 1 + versionName '1.0' + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + buildFeatures { + compose true + } + kotlinOptions { + jvmTarget = '1.8' + } + composeOptions { + kotlinCompilerExtensionVersion '1.3.2' + } +} + +dependencies { + def composeBom = platform('androidx.compose:compose-bom:2023.01.00') + implementation(composeBom) + + implementation 'androidx.activity:activity-compose:1.6.1' + implementation 'androidx.core:core-ktx:1.9.0' + implementation "androidx.compose.ui:ui" + implementation "androidx.compose.material:material" + implementation "androidx.compose.ui:ui-tooling-preview" + debugImplementation "androidx.compose.ui:ui-tooling" +} + +// Compiler flag to use experimental Compose APIs +tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach { + kotlinOptions { + jvmTarget = "1.8" + freeCompilerArgs += [ + "-opt-in=kotlin.RequiresOptIn" + ] + } +} diff --git a/AnimationCodelab/finished/src/main/AndroidManifest.xml b/AnimationCodelab/finished/src/main/AndroidManifest.xml new file mode 100644 index 0000000..3fc22c7 --- /dev/null +++ b/AnimationCodelab/finished/src/main/AndroidManifest.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + diff --git a/AnimationCodelab/finished/src/main/java/com/example/android/codelab/animation/MainActivity.kt b/AnimationCodelab/finished/src/main/java/com/example/android/codelab/animation/MainActivity.kt new file mode 100644 index 0000000..b364f39 --- /dev/null +++ b/AnimationCodelab/finished/src/main/java/com/example/android/codelab/animation/MainActivity.kt @@ -0,0 +1,35 @@ +/* + * Copyright 2021 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.android.codelab.animation + +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import com.example.android.codelab.animation.ui.AnimationCodelabTheme +import com.example.android.codelab.animation.ui.home.Home + +class MainActivity : ComponentActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContent { + AnimationCodelabTheme { + Home() + } + } + } +} diff --git a/AnimationCodelab/finished/src/main/java/com/example/android/codelab/animation/ui/Color.kt b/AnimationCodelab/finished/src/main/java/com/example/android/codelab/animation/ui/Color.kt new file mode 100644 index 0000000..a2fa16c --- /dev/null +++ b/AnimationCodelab/finished/src/main/java/com/example/android/codelab/animation/ui/Color.kt @@ -0,0 +1,27 @@ +/* + * Copyright 2021 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.android.codelab.animation.ui + +import androidx.compose.ui.graphics.Color + +val Purple100 = Color(0xFFE1BEE7) +val Purple500 = Color(0xFF6200EE) +val Purple700 = Color(0xFF3700B3) +val Teal200 = Color(0xFF03DAC5) +val Green300 = Color(0xFF81C784) +val Green800 = Color(0xFF2E7D32) +val Amber600 = Color(0xFFFFB300) diff --git a/AnimationCodelab/finished/src/main/java/com/example/android/codelab/animation/ui/Theme.kt b/AnimationCodelab/finished/src/main/java/com/example/android/codelab/animation/ui/Theme.kt new file mode 100644 index 0000000..12a0fcd --- /dev/null +++ b/AnimationCodelab/finished/src/main/java/com/example/android/codelab/animation/ui/Theme.kt @@ -0,0 +1,34 @@ +/* + * Copyright 2021 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.android.codelab.animation.ui + +import androidx.compose.material.MaterialTheme +import androidx.compose.material.lightColors +import androidx.compose.runtime.Composable + +@Composable +fun AnimationCodelabTheme(content: @Composable () -> Unit) { + val colors = lightColors( + primary = Purple500, + primaryVariant = Purple700, + secondary = Teal200 + ) + MaterialTheme( + colors = colors, + content = content + ) +} diff --git a/AnimationCodelab/finished/src/main/java/com/example/android/codelab/animation/ui/home/Home.kt b/AnimationCodelab/finished/src/main/java/com/example/android/codelab/animation/ui/home/Home.kt new file mode 100644 index 0000000..5ca4a0d --- /dev/null +++ b/AnimationCodelab/finished/src/main/java/com/example/android/codelab/animation/ui/home/Home.kt @@ -0,0 +1,751 @@ +/* + * Copyright 2021 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.android.codelab.animation.ui.home + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.animateColor +import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.animateContentSize +import androidx.compose.animation.core.Animatable +import androidx.compose.animation.core.FastOutLinearInEasing +import androidx.compose.animation.core.LinearOutSlowInEasing +import androidx.compose.animation.core.RepeatMode +import androidx.compose.animation.core.Spring +import androidx.compose.animation.core.animateDp +import androidx.compose.animation.core.animateFloat +import androidx.compose.animation.core.calculateTargetValue +import androidx.compose.animation.core.infiniteRepeatable +import androidx.compose.animation.core.keyframes +import androidx.compose.animation.core.rememberInfiniteTransition +import androidx.compose.animation.core.spring +import androidx.compose.animation.core.tween +import androidx.compose.animation.core.updateTransition +import androidx.compose.animation.slideInVertically +import androidx.compose.animation.slideOutVertically +import androidx.compose.animation.splineBasedDecay +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.foundation.gestures.horizontalDrag +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.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.wrapContentSize +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.ExperimentalMaterialApi +import androidx.compose.material.FloatingActionButton +import androidx.compose.material.Icon +import androidx.compose.material.IconButton +import androidx.compose.material.MaterialTheme +import androidx.compose.material.Scaffold +import androidx.compose.material.Surface +import androidx.compose.material.TabPosition +import androidx.compose.material.TabRow +import androidx.compose.material.Text +import androidx.compose.material.TextButton +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.AccountBox +import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.Edit +import androidx.compose.material.icons.filled.Home +import androidx.compose.material.icons.filled.Info +import androidx.compose.material.icons.filled.Refresh +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateListOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.composed +import androidx.compose.ui.draw.clip +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.input.pointer.positionChange +import androidx.compose.ui.input.pointer.util.VelocityTracker +import androidx.compose.ui.res.stringArrayResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.heading +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.example.android.codelab.animation.R +import com.example.android.codelab.animation.ui.Amber600 +import com.example.android.codelab.animation.ui.AnimationCodelabTheme +import com.example.android.codelab.animation.ui.Green300 +import com.example.android.codelab.animation.ui.Green800 +import com.example.android.codelab.animation.ui.Purple100 +import com.example.android.codelab.animation.ui.Purple700 +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlin.math.absoluteValue +import kotlin.math.roundToInt + +private enum class TabPage { + Home, Work +} + +/** + * Shows the entire screen. + */ +@Composable +fun Home() { + // String resources. + val allTasks = stringArrayResource(R.array.tasks) + val allTopics = stringArrayResource(R.array.topics).toList() + + // The currently selected tab. + var tabPage by remember { mutableStateOf(TabPage.Home) } + + // True if the whether data is currently loading. + var weatherLoading by remember { mutableStateOf(false) } + + // Holds all the tasks currently shown on the task list. + val tasks = remember { mutableStateListOf(*allTasks) } + + // Holds the topic that is currently expanded to show its body. + var expandedTopic by remember { mutableStateOf(null) } + + // True if the message about the edit feature is shown. + var editMessageShown by remember { mutableStateOf(false) } + + // Simulates loading weather data. This takes 3 seconds. + suspend fun loadWeather() { + if (!weatherLoading) { + weatherLoading = true + delay(3000L) + weatherLoading = false + } + } + + // Shows the message about edit feature. + suspend fun showEditMessage() { + if (!editMessageShown) { + editMessageShown = true + delay(3000L) + editMessageShown = false + } + } + + // Load the weather at the initial composition. + LaunchedEffect(Unit) { + loadWeather() + } + + val lazyListState = rememberLazyListState() + + // The background color. The value is changed by the current tab. + val backgroundColor by animateColorAsState(if (tabPage == TabPage.Home) Purple100 else Green300) + + // The coroutine scope for event handlers calling suspend functions. + val coroutineScope = rememberCoroutineScope() + Scaffold( + topBar = { + HomeTabBar( + backgroundColor = backgroundColor, + tabPage = tabPage, + onTabSelected = { tabPage = it } + ) + }, + backgroundColor = backgroundColor, + floatingActionButton = { + HomeFloatingActionButton( + extended = lazyListState.isScrollingUp(), + onClick = { + coroutineScope.launch { + showEditMessage() + } + } + ) + } + ) { padding -> + LazyColumn( + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 32.dp), + state = lazyListState, + modifier = Modifier.padding(padding) + ) { + // Weather + item { Header(title = stringResource(R.string.weather)) } + item { Spacer(modifier = Modifier.height(16.dp)) } + item { + Surface( + modifier = Modifier.fillMaxWidth(), + elevation = 2.dp + ) { + if (weatherLoading) { + LoadingRow() + } else { + WeatherRow(onRefresh = { + coroutineScope.launch { + loadWeather() + } + }) + } + } + } + item { Spacer(modifier = Modifier.height(32.dp)) } + + // Topics + item { Header(title = stringResource(R.string.topics)) } + item { Spacer(modifier = Modifier.height(16.dp)) } + items(allTopics) { topic -> + TopicRow( + topic = topic, + expanded = expandedTopic == topic, + onClick = { + expandedTopic = if (expandedTopic == topic) null else topic + } + ) + } + item { Spacer(modifier = Modifier.height(32.dp)) } + + // Tasks + item { Header(title = stringResource(R.string.tasks)) } + item { Spacer(modifier = Modifier.height(16.dp)) } + if (tasks.isEmpty()) { + item { + TextButton(onClick = { tasks.clear(); tasks.addAll(allTasks) }) { + Text(stringResource(R.string.add_tasks)) + } + } + } + items(count = tasks.size) { i -> + val task = tasks.getOrNull(i) + if (task != null) { + key(task) { + TaskRow( + task = task, + onRemove = { tasks.remove(task) } + ) + } + } + } + } + EditMessage(editMessageShown) + } +} + +/** + * Shows the floating action button. + * + * @param extended Whether the tab should be shown in its expanded state. + */ +// AnimatedVisibility is currently an experimental API in Compose Animation. +@Composable +private fun HomeFloatingActionButton( + extended: Boolean, + onClick: () -> Unit +) { + // Use `FloatingActionButton` rather than `ExtendedFloatingActionButton` for full control on + // how it should animate. + FloatingActionButton(onClick = onClick) { + Row( + modifier = Modifier.padding(horizontal = 16.dp) + ) { + Icon( + imageVector = Icons.Default.Edit, + contentDescription = null + ) + // Toggle the visibility of the content with animation. + AnimatedVisibility(visible = extended) { + Text( + text = stringResource(R.string.edit), + modifier = Modifier + .padding(start = 8.dp, top = 3.dp) + ) + } + } + } +} + +/** + * Shows a message that the edit feature is not available. + */ +@Composable +private fun EditMessage(shown: Boolean) { + AnimatedVisibility( + visible = shown, + enter = slideInVertically( + // Enters by sliding in from offset -fullHeight to 0. + initialOffsetY = { fullHeight -> -fullHeight }, + animationSpec = tween(durationMillis = 150, easing = LinearOutSlowInEasing) + ), + exit = slideOutVertically( + // Exits by sliding out from offset 0 to -fullHeight. + targetOffsetY = { fullHeight -> -fullHeight }, + animationSpec = tween(durationMillis = 250, easing = FastOutLinearInEasing) + ) + ) { + Surface( + modifier = Modifier.fillMaxWidth(), + color = MaterialTheme.colors.secondary, + elevation = 4.dp + ) { + Text( + text = stringResource(R.string.edit_message), + modifier = Modifier.padding(16.dp) + ) + } + } +} + +/** + * Returns whether the lazy list is currently scrolling up. + */ +@Composable +private fun LazyListState.isScrollingUp(): Boolean { + var previousIndex by remember(this) { mutableStateOf(firstVisibleItemIndex) } + var previousScrollOffset by remember(this) { mutableStateOf(firstVisibleItemScrollOffset) } + return remember(this) { + derivedStateOf { + if (previousIndex != firstVisibleItemIndex) { + previousIndex > firstVisibleItemIndex + } else { + previousScrollOffset >= firstVisibleItemScrollOffset + }.also { + previousIndex = firstVisibleItemIndex + previousScrollOffset = firstVisibleItemScrollOffset + } + } + }.value +} + +/** + * Shows the header label. + * + * @param title The title to be shown. + */ +@Composable +private fun Header( + title: String +) { + Text( + text = title, + modifier = Modifier.semantics { heading() }, + style = MaterialTheme.typography.h5 + ) +} + +/** + * Shows a row for one topic. + * + * @param topic The topic title. + * @param expanded Whether the row should be shown expanded with the topic body. + * @param onClick Called when the row is clicked. + */ +@OptIn(ExperimentalMaterialApi::class) +@Composable +private fun TopicRow(topic: String, expanded: Boolean, onClick: () -> Unit) { + TopicRowSpacer(visible = expanded) + Surface( + modifier = Modifier + .fillMaxWidth(), + elevation = 2.dp, + onClick = onClick + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(16.dp) + // This `Column` animates its size when its content changes. + .animateContentSize() + ) { + Row { + Icon( + imageVector = Icons.Default.Info, + contentDescription = null + ) + Spacer(modifier = Modifier.width(16.dp)) + Text( + text = topic, + style = MaterialTheme.typography.body1 + ) + } + if (expanded) { + Spacer(modifier = Modifier.height(8.dp)) + Text( + text = stringResource(R.string.lorem_ipsum), + textAlign = TextAlign.Justify + ) + } + } + } + TopicRowSpacer(visible = expanded) +} + +/** + * Shows a separator for topics. + */ +@Composable +fun TopicRowSpacer(visible: Boolean) { + AnimatedVisibility(visible = visible) { + Spacer(modifier = Modifier.height(8.dp)) + } +} + +/** + * Shows the bar that holds 2 tabs. + * + * @param backgroundColor The background color for the bar. + * @param tabPage The [TabPage] that is currently selected. + * @param onTabSelected Called when the tab is switched. + */ +@Composable +private fun HomeTabBar( + backgroundColor: Color, + tabPage: TabPage, + onTabSelected: (tabPage: TabPage) -> Unit +) { + TabRow( + selectedTabIndex = tabPage.ordinal, + backgroundColor = backgroundColor, + indicator = { tabPositions -> + HomeTabIndicator(tabPositions, tabPage) + } + ) { + HomeTab( + icon = Icons.Default.Home, + title = stringResource(R.string.home), + onClick = { onTabSelected(TabPage.Home) } + ) + HomeTab( + icon = Icons.Default.AccountBox, + title = stringResource(R.string.work), + onClick = { onTabSelected(TabPage.Work) } + ) + } +} + +/** + * Shows an indicator for the tab. + * + * @param tabPositions The list of [TabPosition]s from a [TabRow]. + * @param tabPage The [TabPage] that is currently selected. + */ +@Composable +private fun HomeTabIndicator( + tabPositions: List, + tabPage: TabPage +) { + val transition = updateTransition( + tabPage, + label = "Tab indicator" + ) + val indicatorLeft by transition.animateDp( + transitionSpec = { + if (TabPage.Home isTransitioningTo TabPage.Work) { + // Indicator moves to the right. + // Low stiffness spring for the left edge so it moves slower than the right edge. + spring(stiffness = Spring.StiffnessVeryLow) + } else { + // Indicator moves to the left. + // Medium stiffness spring for the left edge so it moves faster than the right edge. + spring(stiffness = Spring.StiffnessMedium) + } + }, + label = "Indicator left" + ) { page -> + tabPositions[page.ordinal].left + } + val indicatorRight by transition.animateDp( + transitionSpec = { + if (TabPage.Home isTransitioningTo TabPage.Work) { + // Indicator moves to the right + // Medium stiffness spring for the right edge so it moves faster than the left edge. + spring(stiffness = Spring.StiffnessMedium) + } else { + // Indicator moves to the left. + // Low stiffness spring for the right edge so it moves slower than the left edge. + spring(stiffness = Spring.StiffnessVeryLow) + } + }, + label = "Indicator right" + ) { page -> + tabPositions[page.ordinal].right + } + val color by transition.animateColor( + label = "Border color" + ) { page -> + if (page == TabPage.Home) Purple700 else Green800 + } + Box( + Modifier + .fillMaxSize() + .wrapContentSize(align = Alignment.BottomStart) + .offset(x = indicatorLeft) + .width(indicatorRight - indicatorLeft) + .padding(4.dp) + .fillMaxSize() + .border( + BorderStroke(2.dp, color), + RoundedCornerShape(4.dp) + ) + ) +} + +/** + * Shows a tab. + * + * @param icon The icon to be shown on this tab. + * @param title The title to be shown on this tab. + * @param onClick Called when this tab is clicked. + * @param modifier The [Modifier]. + */ +@Composable +private fun HomeTab( + icon: ImageVector, + title: String, + onClick: () -> Unit, + modifier: Modifier = Modifier +) { + Row( + modifier = modifier + .clickable(onClick = onClick) + .padding(16.dp), + horizontalArrangement = Arrangement.Center, + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = icon, + contentDescription = null + ) + Spacer(modifier = Modifier.width(16.dp)) + Text(text = title) + } +} + +/** + * Shows the weather. + * + * @param onRefresh Called when the refresh icon button is clicked. + */ +@Composable +private fun WeatherRow( + onRefresh: () -> Unit +) { + Row( + modifier = Modifier + .heightIn(min = 64.dp) + .padding(16.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Box( + modifier = Modifier + .size(48.dp) + .clip(CircleShape) + .background(Amber600) + ) + Spacer(modifier = Modifier.width(16.dp)) + Text(text = stringResource(R.string.temperature), fontSize = 24.sp) + Spacer(modifier = Modifier.weight(1f)) + IconButton(onClick = onRefresh) { + Icon( + imageVector = Icons.Default.Refresh, + contentDescription = stringResource(R.string.refresh) + ) + } + } +} + +/** + * Shows the loading state of the weather. + */ +@Composable +private fun LoadingRow() { + // Creates an `InfiniteTransition` that runs infinite child animation values. + val infiniteTransition = rememberInfiniteTransition() + val alpha by infiniteTransition.animateFloat( + initialValue = 0f, + targetValue = 1f, + // `infiniteRepeatable` repeats the specified duration-based `AnimationSpec` infinitely. + animationSpec = infiniteRepeatable( + // The `keyframes` animates the value by specifying multiple timestamps. + animation = keyframes { + // One iteration is 1000 milliseconds. + durationMillis = 1000 + // 0.7f at the middle of an iteration. + 0.7f at 500 + }, + // When the value finishes animating from 0f to 1f, it repeats by reversing the + // animation direction. + repeatMode = RepeatMode.Reverse + ) + ) + Row( + modifier = Modifier + .heightIn(min = 64.dp) + .padding(16.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Box( + modifier = Modifier + .size(48.dp) + .clip(CircleShape) + .background(Color.LightGray.copy(alpha = alpha)) + ) + Spacer(modifier = Modifier.width(16.dp)) + Box( + modifier = Modifier + .fillMaxWidth() + .height(32.dp) + .background(Color.LightGray.copy(alpha = alpha)) + ) + } +} + +/** + * Shows a row for one task. + * + * @param task The task description. + * @param onRemove Called when the task is swiped away and removed. + */ +@Composable +private fun TaskRow(task: String, onRemove: () -> Unit) { + Surface( + modifier = Modifier + .fillMaxWidth() + .swipeToDismiss(onRemove), + elevation = 2.dp + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(16.dp) + ) { + Icon( + imageVector = Icons.Default.Check, + contentDescription = null + ) + Spacer(modifier = Modifier.width(16.dp)) + Text( + text = task, + style = MaterialTheme.typography.body1 + ) + } + } +} + +/** + * The modified element can be horizontally swiped away. + * + * @param onDismissed Called when the element is swiped to the edge of the screen. + */ +private fun Modifier.swipeToDismiss( + onDismissed: () -> Unit +): Modifier = composed { + // This `Animatable` stores the horizontal offset for the element. + val offsetX = remember { Animatable(0f) } + pointerInput(Unit) { + // Used to calculate a settling position of a fling animation. + val decay = splineBasedDecay(this) + // Wrap in a coroutine scope to use suspend functions for touch events and animation. + coroutineScope { + while (true) { + // Wait for a touch down event. + val pointerId = awaitPointerEventScope { awaitFirstDown().id } + // Interrupt any ongoing animation. + offsetX.stop() + // Prepare for drag events and record velocity of a fling. + val velocityTracker = VelocityTracker() + // Wait for drag events. + awaitPointerEventScope { + horizontalDrag(pointerId) { change -> + // Record the position after offset + val horizontalDragOffset = offsetX.value + change.positionChange().x + launch { + // Overwrite the `Animatable` value while the element is dragged. + offsetX.snapTo(horizontalDragOffset) + } + // Record the velocity of the drag. + velocityTracker.addPosition(change.uptimeMillis, change.position) + // Consume the gesture event, not passed to external + if (change.positionChange() != Offset.Zero) change.consume() + } + } + // Dragging finished. Calculate the velocity of the fling. + val velocity = velocityTracker.calculateVelocity().x + // Calculate where the element eventually settles after the fling animation. + val targetOffsetX = decay.calculateTargetValue(offsetX.value, velocity) + // The animation should end as soon as it reaches these bounds. + offsetX.updateBounds( + lowerBound = -size.width.toFloat(), + upperBound = size.width.toFloat() + ) + launch { + if (targetOffsetX.absoluteValue <= size.width) { + // Not enough velocity; Slide back to the default position. + offsetX.animateTo(targetValue = 0f, initialVelocity = velocity) + } else { + // Enough velocity to slide away the element to the edge. + offsetX.animateDecay(velocity, decay) + // The element was swiped away. + onDismissed() + } + } + } + } + } + // Apply the horizontal offset to the element. + .offset { IntOffset(offsetX.value.roundToInt(), 0) } +} + +@Preview +@Composable +private fun PreviewHomeTabBar() { + HomeTabBar( + backgroundColor = Purple100, + tabPage = TabPage.Home, + onTabSelected = {} + ) +} + +@Preview +@Composable +private fun PreviewHome() { + AnimationCodelabTheme { + Home() + } +} diff --git a/AnimationCodelab/finished/src/main/res/drawable/ic_launcher_foreground.xml b/AnimationCodelab/finished/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..ad5eee7 --- /dev/null +++ b/AnimationCodelab/finished/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,157 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AnimationCodelab/finished/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/AnimationCodelab/finished/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..8368754 --- /dev/null +++ b/AnimationCodelab/finished/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,20 @@ + + + + + + diff --git a/AnimationCodelab/finished/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/AnimationCodelab/finished/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..8368754 --- /dev/null +++ b/AnimationCodelab/finished/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,20 @@ + + + + + + diff --git a/AnimationCodelab/finished/src/main/res/mipmap-hdpi/ic_launcher.png b/AnimationCodelab/finished/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..99cca7a Binary files /dev/null and b/AnimationCodelab/finished/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/AnimationCodelab/finished/src/main/res/mipmap-hdpi/ic_launcher_round.png b/AnimationCodelab/finished/src/main/res/mipmap-hdpi/ic_launcher_round.png new file mode 100644 index 0000000..65cf45d Binary files /dev/null and b/AnimationCodelab/finished/src/main/res/mipmap-hdpi/ic_launcher_round.png differ diff --git a/AnimationCodelab/finished/src/main/res/mipmap-mdpi/ic_launcher.png b/AnimationCodelab/finished/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..4ade24b Binary files /dev/null and b/AnimationCodelab/finished/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/AnimationCodelab/finished/src/main/res/mipmap-mdpi/ic_launcher_round.png b/AnimationCodelab/finished/src/main/res/mipmap-mdpi/ic_launcher_round.png new file mode 100644 index 0000000..cd5c869 Binary files /dev/null and b/AnimationCodelab/finished/src/main/res/mipmap-mdpi/ic_launcher_round.png differ diff --git a/AnimationCodelab/finished/src/main/res/mipmap-xhdpi/ic_launcher.png b/AnimationCodelab/finished/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..d1d81c7 Binary files /dev/null and b/AnimationCodelab/finished/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/AnimationCodelab/finished/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/AnimationCodelab/finished/src/main/res/mipmap-xhdpi/ic_launcher_round.png new file mode 100644 index 0000000..16f16d4 Binary files /dev/null and b/AnimationCodelab/finished/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/AnimationCodelab/finished/src/main/res/mipmap-xxhdpi/ic_launcher.png b/AnimationCodelab/finished/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..03cc020 Binary files /dev/null and b/AnimationCodelab/finished/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/AnimationCodelab/finished/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/AnimationCodelab/finished/src/main/res/mipmap-xxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..e58f2aa Binary files /dev/null and b/AnimationCodelab/finished/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/AnimationCodelab/finished/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/AnimationCodelab/finished/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..8c4ab2a Binary files /dev/null and b/AnimationCodelab/finished/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/AnimationCodelab/finished/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/AnimationCodelab/finished/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..863363d Binary files /dev/null and b/AnimationCodelab/finished/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/AnimationCodelab/finished/src/main/res/values/colors.xml b/AnimationCodelab/finished/src/main/res/values/colors.xml new file mode 100644 index 0000000..81798f0 --- /dev/null +++ b/AnimationCodelab/finished/src/main/res/values/colors.xml @@ -0,0 +1,21 @@ + + + + #FFE1BEE7 + #FF6200EE + #FF3700B3 + diff --git a/AnimationCodelab/finished/src/main/res/values/strings.xml b/AnimationCodelab/finished/src/main/res/values/strings.xml new file mode 100644 index 0000000..d59e408 --- /dev/null +++ b/AnimationCodelab/finished/src/main/res/values/strings.xml @@ -0,0 +1,44 @@ + + + + AnimationCodelab + Home + Work + Weather + 18 ℃ + Tasks + ADD TASKS + + Buy milk + Choose curtain + Plant rosemary + Finish the essay + Receive new packages + Take a photo + + Topics + + 2 new packages arrived + DIY project recommendation + Festival next month + New flower seeds available + + Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. + EDIT + Edit feature is not supported + Refresh + diff --git a/AnimationCodelab/finished/src/main/res/values/themes.xml b/AnimationCodelab/finished/src/main/res/values/themes.xml new file mode 100644 index 0000000..1423958 --- /dev/null +++ b/AnimationCodelab/finished/src/main/res/values/themes.xml @@ -0,0 +1,22 @@ + + + + + diff --git a/AnimationCodelab/gradle.properties b/AnimationCodelab/gradle.properties new file mode 100644 index 0000000..2ec1b00 --- /dev/null +++ b/AnimationCodelab/gradle.properties @@ -0,0 +1,22 @@ +# Project-wide Gradle settings. +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html + +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx2048m + +org.gradle.configureondemand=true +org.gradle.caching=true +org.gradle.parallel=true + +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app's APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true + +# Kotlin code style for this project: "official" or "obsolete": +kotlin.code.style=official diff --git a/AnimationCodelab/gradle/wrapper/gradle-wrapper.jar b/AnimationCodelab/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..943f0cb Binary files /dev/null and b/AnimationCodelab/gradle/wrapper/gradle-wrapper.jar differ diff --git a/AnimationCodelab/gradle/wrapper/gradle-wrapper.properties b/AnimationCodelab/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..f398c33 --- /dev/null +++ b/AnimationCodelab/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/AnimationCodelab/gradlew b/AnimationCodelab/gradlew new file mode 100644 index 0000000..65dcd68 --- /dev/null +++ b/AnimationCodelab/gradlew @@ -0,0 +1,244 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# 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. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/AnimationCodelab/gradlew.bat b/AnimationCodelab/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/AnimationCodelab/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/AnimationCodelab/ic_launcher-web.png b/AnimationCodelab/ic_launcher-web.png new file mode 100644 index 0000000..0d6c5eb Binary files /dev/null and b/AnimationCodelab/ic_launcher-web.png differ diff --git a/AnimationCodelab/screenshots/app.png b/AnimationCodelab/screenshots/app.png new file mode 100644 index 0000000..4621c4a Binary files /dev/null and b/AnimationCodelab/screenshots/app.png differ diff --git a/AnimationCodelab/settings.gradle b/AnimationCodelab/settings.gradle new file mode 100644 index 0000000..9ca8f5f --- /dev/null +++ b/AnimationCodelab/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = "AnimationCodelab" +include ':finished', ':start' diff --git a/AnimationCodelab/start/.gitignore b/AnimationCodelab/start/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/AnimationCodelab/start/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/AnimationCodelab/start/build.gradle b/AnimationCodelab/start/build.gradle new file mode 100644 index 0000000..d8b257e --- /dev/null +++ b/AnimationCodelab/start/build.gradle @@ -0,0 +1,66 @@ +/* + * Copyright 2021 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. + */ + +plugins { + id 'com.android.application' + id 'kotlin-android' +} + +android { + compileSdkVersion 33 + defaultConfig { + applicationId 'com.example.android.codelab.animation' + minSdkVersion 21 + targetSdkVersion 33 + versionCode 1 + versionName '1.0' + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + buildFeatures { + compose true + } + kotlinOptions { + jvmTarget = '1.8' + } + composeOptions { + kotlinCompilerExtensionVersion '1.3.2' + } +} + +dependencies { + def composeBom = platform('androidx.compose:compose-bom:2023.01.00') + implementation(composeBom) + + implementation 'androidx.activity:activity-compose:1.6.1' + implementation 'androidx.core:core-ktx:1.9.0' + implementation "androidx.compose.ui:ui" + implementation "androidx.compose.material:material" + implementation "androidx.compose.ui:ui-tooling-preview" + debugImplementation "androidx.compose.ui:ui-tooling" +} + +// Compiler flag to use experimental Compose APIs +tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach { + kotlinOptions { + jvmTarget = "1.8" + freeCompilerArgs += [ + "-opt-in=kotlin.RequiresOptIn" + ] + } +} diff --git a/AnimationCodelab/start/src/main/AndroidManifest.xml b/AnimationCodelab/start/src/main/AndroidManifest.xml new file mode 100644 index 0000000..3fc22c7 --- /dev/null +++ b/AnimationCodelab/start/src/main/AndroidManifest.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + diff --git a/AnimationCodelab/start/src/main/java/com/example/android/codelab/animation/MainActivity.kt b/AnimationCodelab/start/src/main/java/com/example/android/codelab/animation/MainActivity.kt new file mode 100644 index 0000000..b364f39 --- /dev/null +++ b/AnimationCodelab/start/src/main/java/com/example/android/codelab/animation/MainActivity.kt @@ -0,0 +1,35 @@ +/* + * Copyright 2021 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.android.codelab.animation + +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import com.example.android.codelab.animation.ui.AnimationCodelabTheme +import com.example.android.codelab.animation.ui.home.Home + +class MainActivity : ComponentActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContent { + AnimationCodelabTheme { + Home() + } + } + } +} diff --git a/AnimationCodelab/start/src/main/java/com/example/android/codelab/animation/ui/Color.kt b/AnimationCodelab/start/src/main/java/com/example/android/codelab/animation/ui/Color.kt new file mode 100644 index 0000000..a2fa16c --- /dev/null +++ b/AnimationCodelab/start/src/main/java/com/example/android/codelab/animation/ui/Color.kt @@ -0,0 +1,27 @@ +/* + * Copyright 2021 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.android.codelab.animation.ui + +import androidx.compose.ui.graphics.Color + +val Purple100 = Color(0xFFE1BEE7) +val Purple500 = Color(0xFF6200EE) +val Purple700 = Color(0xFF3700B3) +val Teal200 = Color(0xFF03DAC5) +val Green300 = Color(0xFF81C784) +val Green800 = Color(0xFF2E7D32) +val Amber600 = Color(0xFFFFB300) diff --git a/AnimationCodelab/start/src/main/java/com/example/android/codelab/animation/ui/Theme.kt b/AnimationCodelab/start/src/main/java/com/example/android/codelab/animation/ui/Theme.kt new file mode 100644 index 0000000..12a0fcd --- /dev/null +++ b/AnimationCodelab/start/src/main/java/com/example/android/codelab/animation/ui/Theme.kt @@ -0,0 +1,34 @@ +/* + * Copyright 2021 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.android.codelab.animation.ui + +import androidx.compose.material.MaterialTheme +import androidx.compose.material.lightColors +import androidx.compose.runtime.Composable + +@Composable +fun AnimationCodelabTheme(content: @Composable () -> Unit) { + val colors = lightColors( + primary = Purple500, + primaryVariant = Purple700, + secondary = Teal200 + ) + MaterialTheme( + colors = colors, + content = content + ) +} diff --git a/AnimationCodelab/start/src/main/java/com/example/android/codelab/animation/ui/home/Home.kt b/AnimationCodelab/start/src/main/java/com/example/android/codelab/animation/ui/home/Home.kt new file mode 100644 index 0000000..ecd6070 --- /dev/null +++ b/AnimationCodelab/start/src/main/java/com/example/android/codelab/animation/ui/home/Home.kt @@ -0,0 +1,654 @@ +/* + * Copyright 2021 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.android.codelab.animation.ui.home + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.splineBasedDecay +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.foundation.gestures.horizontalDrag +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.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.wrapContentSize +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.ExperimentalMaterialApi +import androidx.compose.material.FloatingActionButton +import androidx.compose.material.Icon +import androidx.compose.material.IconButton +import androidx.compose.material.MaterialTheme +import androidx.compose.material.Scaffold +import androidx.compose.material.Surface +import androidx.compose.material.TabPosition +import androidx.compose.material.TabRow +import androidx.compose.material.Text +import androidx.compose.material.TextButton +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.AccountBox +import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.Edit +import androidx.compose.material.icons.filled.Home +import androidx.compose.material.icons.filled.Info +import androidx.compose.material.icons.filled.Refresh +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateListOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.composed +import androidx.compose.ui.draw.clip +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.input.pointer.positionChange +import androidx.compose.ui.input.pointer.util.VelocityTracker +import androidx.compose.ui.res.stringArrayResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.heading +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.example.android.codelab.animation.R +import com.example.android.codelab.animation.ui.Amber600 +import com.example.android.codelab.animation.ui.AnimationCodelabTheme +import com.example.android.codelab.animation.ui.Green300 +import com.example.android.codelab.animation.ui.Green800 +import com.example.android.codelab.animation.ui.Purple100 +import com.example.android.codelab.animation.ui.Purple700 +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch + +private enum class TabPage { + Home, Work +} + +/** + * Shows the entire screen. + */ +@Composable +fun Home() { + // String resources. + val allTasks = stringArrayResource(R.array.tasks) + val allTopics = stringArrayResource(R.array.topics).toList() + + // The currently selected tab. + var tabPage by remember { mutableStateOf(TabPage.Home) } + + // True if the whether data is currently loading. + var weatherLoading by remember { mutableStateOf(false) } + + // Holds all the tasks currently shown on the task list. + val tasks = remember { mutableStateListOf(*allTasks) } + + // Holds the topic that is currently expanded to show its body. + var expandedTopic by remember { mutableStateOf(null) } + + // True if the message about the edit feature is shown. + var editMessageShown by remember { mutableStateOf(false) } + + // Simulates loading weather data. This takes 3 seconds. + suspend fun loadWeather() { + if (!weatherLoading) { + weatherLoading = true + delay(3000L) + weatherLoading = false + } + } + + // Shows the message about edit feature. + suspend fun showEditMessage() { + if (!editMessageShown) { + editMessageShown = true + delay(3000L) + editMessageShown = false + } + } + + // Load the weather at the initial composition. + LaunchedEffect(Unit) { + loadWeather() + } + + val lazyListState = rememberLazyListState() + + // The background color. The value is changed by the current tab. + // TODO 1: Animate this color change. + val backgroundColor = if (tabPage == TabPage.Home) Purple100 else Green300 + + // The coroutine scope for event handlers calling suspend functions. + val coroutineScope = rememberCoroutineScope() + Scaffold( + topBar = { + HomeTabBar( + backgroundColor = backgroundColor, + tabPage = tabPage, + onTabSelected = { tabPage = it } + ) + }, + backgroundColor = backgroundColor, + floatingActionButton = { + HomeFloatingActionButton( + extended = lazyListState.isScrollingUp(), + onClick = { + coroutineScope.launch { + showEditMessage() + } + } + ) + } + ) { padding -> + LazyColumn( + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 32.dp), + state = lazyListState, + modifier = Modifier.padding(padding) + ) { + // Weather + item { Header(title = stringResource(R.string.weather)) } + item { Spacer(modifier = Modifier.height(16.dp)) } + item { + Surface( + modifier = Modifier.fillMaxWidth(), + elevation = 2.dp + ) { + if (weatherLoading) { + LoadingRow() + } else { + WeatherRow(onRefresh = { + coroutineScope.launch { + loadWeather() + } + }) + } + } + } + item { Spacer(modifier = Modifier.height(32.dp)) } + + // Topics + item { Header(title = stringResource(R.string.topics)) } + item { Spacer(modifier = Modifier.height(16.dp)) } + items(allTopics) { topic -> + TopicRow( + topic = topic, + expanded = expandedTopic == topic, + onClick = { + expandedTopic = if (expandedTopic == topic) null else topic + } + ) + } + item { Spacer(modifier = Modifier.height(32.dp)) } + + // Tasks + item { Header(title = stringResource(R.string.tasks)) } + item { Spacer(modifier = Modifier.height(16.dp)) } + if (tasks.isEmpty()) { + item { + TextButton(onClick = { tasks.clear(); tasks.addAll(allTasks) }) { + Text(stringResource(R.string.add_tasks)) + } + } + } + items(count = tasks.size) { i -> + val task = tasks.getOrNull(i) + if (task != null) { + key(task) { + TaskRow( + task = task, + onRemove = { tasks.remove(task) } + ) + } + } + } + } + EditMessage(editMessageShown) + } +} + +/** + * Shows the floating action button. + * + * @param extended Whether the tab should be shown in its expanded state. + */ +// AnimatedVisibility is currently an experimental API in Compose Animation. +@Composable +private fun HomeFloatingActionButton( + extended: Boolean, + onClick: () -> Unit +) { + // Use `FloatingActionButton` rather than `ExtendedFloatingActionButton` for full control on + // how it should animate. + FloatingActionButton(onClick = onClick) { + Row( + modifier = Modifier.padding(horizontal = 16.dp) + ) { + Icon( + imageVector = Icons.Default.Edit, + contentDescription = null + ) + // Toggle the visibility of the content with animation. + // TODO 2-1: Animate this visibility change. + if (extended) { + Text( + text = stringResource(R.string.edit), + modifier = Modifier + .padding(start = 8.dp, top = 3.dp) + ) + } + } + } +} + +/** + * Shows a message that the edit feature is not available. + */ +@Composable +private fun EditMessage(shown: Boolean) { + // TODO 2-2: The message should slide down from the top on appearance and slide up on + // disappearance. + AnimatedVisibility( + visible = shown + ) { + Surface( + modifier = Modifier.fillMaxWidth(), + color = MaterialTheme.colors.secondary, + elevation = 4.dp + ) { + Text( + text = stringResource(R.string.edit_message), + modifier = Modifier.padding(16.dp) + ) + } + } +} + +/** + * Returns whether the lazy list is currently scrolling up. + */ +@Composable +private fun LazyListState.isScrollingUp(): Boolean { + var previousIndex by remember(this) { mutableStateOf(firstVisibleItemIndex) } + var previousScrollOffset by remember(this) { mutableStateOf(firstVisibleItemScrollOffset) } + return remember(this) { + derivedStateOf { + if (previousIndex != firstVisibleItemIndex) { + previousIndex > firstVisibleItemIndex + } else { + previousScrollOffset >= firstVisibleItemScrollOffset + }.also { + previousIndex = firstVisibleItemIndex + previousScrollOffset = firstVisibleItemScrollOffset + } + } + }.value +} + +/** + * Shows the header label. + * + * @param title The title to be shown. + */ +@Composable +private fun Header( + title: String +) { + Text( + text = title, + modifier = Modifier.semantics { heading() }, + style = MaterialTheme.typography.h5 + ) +} + +/** + * Shows a row for one topic. + * + * @param topic The topic title. + * @param expanded Whether the row should be shown expanded with the topic body. + * @param onClick Called when the row is clicked. + */ +@OptIn(ExperimentalMaterialApi::class) +@Composable +private fun TopicRow(topic: String, expanded: Boolean, onClick: () -> Unit) { + TopicRowSpacer(visible = expanded) + Surface( + modifier = Modifier + .fillMaxWidth(), + elevation = 2.dp, + onClick = onClick + ) { + // TODO 3: Animate the size change of the content. + Column( + modifier = Modifier + .fillMaxWidth() + .padding(16.dp) + ) { + Row { + Icon( + imageVector = Icons.Default.Info, + contentDescription = null + ) + Spacer(modifier = Modifier.width(16.dp)) + Text( + text = topic, + style = MaterialTheme.typography.body1 + ) + } + if (expanded) { + Spacer(modifier = Modifier.height(8.dp)) + Text( + text = stringResource(R.string.lorem_ipsum), + textAlign = TextAlign.Justify + ) + } + } + } + TopicRowSpacer(visible = expanded) +} + +/** + * Shows a separator for topics. + */ +@Composable +fun TopicRowSpacer(visible: Boolean) { + AnimatedVisibility(visible = visible) { + Spacer(modifier = Modifier.height(8.dp)) + } +} + +/** + * Shows the bar that holds 2 tabs. + * + * @param backgroundColor The background color for the bar. + * @param tabPage The [TabPage] that is currently selected. + * @param onTabSelected Called when the tab is switched. + */ +@Composable +private fun HomeTabBar( + backgroundColor: Color, + tabPage: TabPage, + onTabSelected: (tabPage: TabPage) -> Unit +) { + TabRow( + selectedTabIndex = tabPage.ordinal, + backgroundColor = backgroundColor, + indicator = { tabPositions -> + HomeTabIndicator(tabPositions, tabPage) + } + ) { + HomeTab( + icon = Icons.Default.Home, + title = stringResource(R.string.home), + onClick = { onTabSelected(TabPage.Home) } + ) + HomeTab( + icon = Icons.Default.AccountBox, + title = stringResource(R.string.work), + onClick = { onTabSelected(TabPage.Work) } + ) + } +} + +/** + * Shows an indicator for the tab. + * + * @param tabPositions The list of [TabPosition]s from a [TabRow]. + * @param tabPage The [TabPage] that is currently selected. + */ +@Composable +private fun HomeTabIndicator( + tabPositions: List, + tabPage: TabPage +) { + // TODO 4: Animate these value changes. + val indicatorLeft = tabPositions[tabPage.ordinal].left + val indicatorRight = tabPositions[tabPage.ordinal].right + val color = if (tabPage == TabPage.Home) Purple700 else Green800 + Box( + Modifier + .fillMaxSize() + .wrapContentSize(align = Alignment.BottomStart) + .offset(x = indicatorLeft) + .width(indicatorRight - indicatorLeft) + .padding(4.dp) + .fillMaxSize() + .border( + BorderStroke(2.dp, color), + RoundedCornerShape(4.dp) + ) + ) +} + +/** + * Shows a tab. + * + * @param icon The icon to be shown on this tab. + * @param title The title to be shown on this tab. + * @param onClick Called when this tab is clicked. + * @param modifier The [Modifier]. + */ +@Composable +private fun HomeTab( + icon: ImageVector, + title: String, + onClick: () -> Unit, + modifier: Modifier = Modifier +) { + Row( + modifier = modifier + .clickable(onClick = onClick) + .padding(16.dp), + horizontalArrangement = Arrangement.Center, + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = icon, + contentDescription = null + ) + Spacer(modifier = Modifier.width(16.dp)) + Text(text = title) + } +} + +/** + * Shows the weather. + * + * @param onRefresh Called when the refresh icon button is clicked. + */ +@Composable +private fun WeatherRow( + onRefresh: () -> Unit +) { + Row( + modifier = Modifier + .heightIn(min = 64.dp) + .padding(16.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Box( + modifier = Modifier + .size(48.dp) + .clip(CircleShape) + .background(Amber600) + ) + Spacer(modifier = Modifier.width(16.dp)) + Text(text = stringResource(R.string.temperature), fontSize = 24.sp) + Spacer(modifier = Modifier.weight(1f)) + IconButton(onClick = onRefresh) { + Icon( + imageVector = Icons.Default.Refresh, + contentDescription = stringResource(R.string.refresh) + ) + } + } +} + +/** + * Shows the loading state of the weather. + */ +@Composable +private fun LoadingRow() { + // TODO 5: Animate this value between 0f and 1f, then back to 0f repeatedly. + val alpha = 1f + Row( + modifier = Modifier + .heightIn(min = 64.dp) + .padding(16.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Box( + modifier = Modifier + .size(48.dp) + .clip(CircleShape) + .background(Color.LightGray.copy(alpha = alpha)) + ) + Spacer(modifier = Modifier.width(16.dp)) + Box( + modifier = Modifier + .fillMaxWidth() + .height(32.dp) + .background(Color.LightGray.copy(alpha = alpha)) + ) + } +} + +/** + * Shows a row for one task. + * + * @param task The task description. + * @param onRemove Called when the task is swiped away and removed. + */ +@Composable +private fun TaskRow(task: String, onRemove: () -> Unit) { + Surface( + modifier = Modifier + .fillMaxWidth() + .swipeToDismiss(onRemove), + elevation = 2.dp + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(16.dp) + ) { + Icon( + imageVector = Icons.Default.Check, + contentDescription = null + ) + Spacer(modifier = Modifier.width(16.dp)) + Text( + text = task, + style = MaterialTheme.typography.body1 + ) + } + } +} + +/** + * The modified element can be horizontally swiped away. + * + * @param onDismissed Called when the element is swiped to the edge of the screen. + */ +private fun Modifier.swipeToDismiss( + onDismissed: () -> Unit +): Modifier = composed { + // TODO 6-1: Create an Animatable instance for the offset of the swiped element. + pointerInput(Unit) { + // Used to calculate a settling position of a fling animation. + val decay = splineBasedDecay(this) + // Wrap in a coroutine scope to use suspend functions for touch events and animation. + coroutineScope { + while (true) { + // Wait for a touch down event. + val pointerId = awaitPointerEventScope { awaitFirstDown().id } + // TODO 6-2: Touch detected; the animation should be stopped. + // Prepare for drag events and record velocity of a fling. + val velocityTracker = VelocityTracker() + // Wait for drag events. + awaitPointerEventScope { + horizontalDrag(pointerId) { change -> + // TODO 6-3: Apply the drag change to the Animatable offset. + // Record the velocity of the drag. + velocityTracker.addPosition(change.uptimeMillis, change.position) + // Consume the gesture event, not passed to external + if (change.positionChange() != Offset.Zero) change.consume() + } + } + // Dragging finished. Calculate the velocity of the fling. + val velocity = velocityTracker.calculateVelocity().x + // TODO 6-4: Calculate the eventual position where the fling should settle + // based on the current offset value and velocity + // TODO 6-5: Set the upper and lower bounds so that the animation stops when it + // reaches the edge. + launch { + // TODO 6-6: Slide back the element if the settling position does not go beyond + // the size of the element. Remove the element if it does. + } + } + } + } + .offset { + // TODO 6-7: Use the animating offset value here. + IntOffset(0, 0) + } +} + +@Preview +@Composable +private fun PreviewHomeTabBar() { + HomeTabBar( + backgroundColor = Purple100, + tabPage = TabPage.Home, + onTabSelected = {} + ) +} + +@Preview +@Composable +private fun PreviewHome() { + AnimationCodelabTheme { + Home() + } +} diff --git a/AnimationCodelab/start/src/main/res/drawable/ic_launcher_foreground.xml b/AnimationCodelab/start/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..ad5eee7 --- /dev/null +++ b/AnimationCodelab/start/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,157 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AnimationCodelab/start/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/AnimationCodelab/start/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..8368754 --- /dev/null +++ b/AnimationCodelab/start/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,20 @@ + + + + + + diff --git a/AnimationCodelab/start/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/AnimationCodelab/start/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..8368754 --- /dev/null +++ b/AnimationCodelab/start/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,20 @@ + + + + + + diff --git a/AnimationCodelab/start/src/main/res/mipmap-hdpi/ic_launcher.png b/AnimationCodelab/start/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..99cca7a Binary files /dev/null and b/AnimationCodelab/start/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/AnimationCodelab/start/src/main/res/mipmap-hdpi/ic_launcher_round.png b/AnimationCodelab/start/src/main/res/mipmap-hdpi/ic_launcher_round.png new file mode 100644 index 0000000..65cf45d Binary files /dev/null and b/AnimationCodelab/start/src/main/res/mipmap-hdpi/ic_launcher_round.png differ diff --git a/AnimationCodelab/start/src/main/res/mipmap-mdpi/ic_launcher.png b/AnimationCodelab/start/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..4ade24b Binary files /dev/null and b/AnimationCodelab/start/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/AnimationCodelab/start/src/main/res/mipmap-mdpi/ic_launcher_round.png b/AnimationCodelab/start/src/main/res/mipmap-mdpi/ic_launcher_round.png new file mode 100644 index 0000000..cd5c869 Binary files /dev/null and b/AnimationCodelab/start/src/main/res/mipmap-mdpi/ic_launcher_round.png differ diff --git a/AnimationCodelab/start/src/main/res/mipmap-xhdpi/ic_launcher.png b/AnimationCodelab/start/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..d1d81c7 Binary files /dev/null and b/AnimationCodelab/start/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/AnimationCodelab/start/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/AnimationCodelab/start/src/main/res/mipmap-xhdpi/ic_launcher_round.png new file mode 100644 index 0000000..16f16d4 Binary files /dev/null and b/AnimationCodelab/start/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/AnimationCodelab/start/src/main/res/mipmap-xxhdpi/ic_launcher.png b/AnimationCodelab/start/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..03cc020 Binary files /dev/null and b/AnimationCodelab/start/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/AnimationCodelab/start/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/AnimationCodelab/start/src/main/res/mipmap-xxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..e58f2aa Binary files /dev/null and b/AnimationCodelab/start/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/AnimationCodelab/start/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/AnimationCodelab/start/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..8c4ab2a Binary files /dev/null and b/AnimationCodelab/start/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/AnimationCodelab/start/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/AnimationCodelab/start/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..863363d Binary files /dev/null and b/AnimationCodelab/start/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/AnimationCodelab/start/src/main/res/values/colors.xml b/AnimationCodelab/start/src/main/res/values/colors.xml new file mode 100644 index 0000000..81798f0 --- /dev/null +++ b/AnimationCodelab/start/src/main/res/values/colors.xml @@ -0,0 +1,21 @@ + + + + #FFE1BEE7 + #FF6200EE + #FF3700B3 + diff --git a/AnimationCodelab/start/src/main/res/values/strings.xml b/AnimationCodelab/start/src/main/res/values/strings.xml new file mode 100644 index 0000000..d59e408 --- /dev/null +++ b/AnimationCodelab/start/src/main/res/values/strings.xml @@ -0,0 +1,44 @@ + + + + AnimationCodelab + Home + Work + Weather + 18 ℃ + Tasks + ADD TASKS + + Buy milk + Choose curtain + Plant rosemary + Finish the essay + Receive new packages + Take a photo + + Topics + + 2 new packages arrived + DIY project recommendation + Festival next month + New flower seeds available + + Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. + EDIT + Edit feature is not supported + Refresh + diff --git a/AnimationCodelab/start/src/main/res/values/themes.xml b/AnimationCodelab/start/src/main/res/values/themes.xml new file mode 100644 index 0000000..1423958 --- /dev/null +++ b/AnimationCodelab/start/src/main/res/values/themes.xml @@ -0,0 +1,22 @@ + + + + +