├── .gitignore
├── .idea
├── .gitignore
└── codeStyles
│ ├── Project.xml
│ └── codeStyleConfig.xml
├── LICENSE
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── me
│ │ └── onebone
│ │ └── toolbar
│ │ └── ExampleInstrumentedTest.kt
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── me
│ │ │ └── onebone
│ │ │ └── toolbar
│ │ │ ├── MainActivity.kt
│ │ │ ├── ParallaxActivity.kt
│ │ │ └── ui
│ │ │ └── theme
│ │ │ ├── Color.kt
│ │ │ ├── Shape.kt
│ │ │ ├── Theme.kt
│ │ │ └── Type.kt
│ └── res
│ │ ├── drawable-v24
│ │ └── ic_launcher_foreground.xml
│ │ ├── drawable
│ │ ├── android.png
│ │ └── ic_launcher_background.xml
│ │ ├── mipmap-anydpi-v26
│ │ ├── ic_launcher.xml
│ │ └── ic_launcher_round.xml
│ │ ├── mipmap-hdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── values-night
│ │ └── themes.xml
│ │ └── values
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── themes.xml
│ └── test
│ └── java
│ └── me
│ └── onebone
│ └── toolbar
│ └── ExampleUnitTest.kt
├── build.gradle
├── gradle.properties
├── gradle
├── publish.gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── img
├── enter-always-collapsed.gif
├── enter-always.gif
└── exit-until-collapsed.gif
├── lib
├── .gitignore
├── build.gradle
├── consumer-rules.pro
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── me
│ │ └── onebone
│ │ └── toolbar
│ │ ├── CollapsingToolbarTest.kt
│ │ └── ExampleInstrumentedTest.kt
│ ├── main
│ ├── AndroidManifest.xml
│ └── java
│ │ └── me
│ │ └── onebone
│ │ └── toolbar
│ │ ├── Annotations.kt
│ │ ├── AppBarContainer.kt
│ │ ├── CollapsingToolbar.kt
│ │ ├── CollapsingToolbarScaffold.kt
│ │ ├── FabPlacement.kt
│ │ ├── FabPosition.kt
│ │ ├── ScrollStrategy.kt
│ │ └── ToolbarWithFabScaffold.kt
│ └── test
│ └── java
│ └── me
│ └── onebone
│ └── toolbar
│ └── ExampleUnitTest.kt
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by https://www.toptal.com/developers/gitignore/api/android,androidstudio
2 | # Edit at https://www.toptal.com/developers/gitignore?templates=android,androidstudio
3 |
4 | ### Android ###
5 | # Built application files
6 | *.apk
7 | *.aar
8 | *.ap_
9 | *.aab
10 |
11 | # Files for the ART/Dalvik VM
12 | *.dex
13 |
14 | # Java class files
15 | *.class
16 |
17 | # Generated files
18 | bin/
19 | gen/
20 | out/
21 | # Uncomment the following line in case you need and you don't have the release build type files in your app
22 | # release/
23 |
24 | # Gradle files
25 | .gradle/
26 | build/
27 |
28 | # Local configuration file (sdk path, etc)
29 | local.properties
30 |
31 | # Proguard folder generated by Eclipse
32 | proguard/
33 |
34 | # Log Files
35 | *.log
36 |
37 | # Android Studio Navigation editor temp files
38 | .navigation/
39 |
40 | # Android Studio captures folder
41 | captures/
42 |
43 | # IntelliJ
44 | *.iml
45 | .idea/workspace.xml
46 | .idea/tasks.xml
47 | .idea/gradle.xml
48 | .idea/assetWizardSettings.xml
49 | .idea/dictionaries
50 | .idea/libraries
51 | # Android Studio 3 in .gitignore file.
52 | .idea/caches
53 | .idea/modules.xml
54 | # Comment next line if keeping position of elements in Navigation Editor is relevant for you
55 | .idea/navEditor.xml
56 |
57 | .idea/deploymentTargetDropDown.xml
58 |
59 | # Keystore files
60 | # Uncomment the following lines if you do not want to check your keystore files in.
61 | #*.jks
62 | #*.keystore
63 |
64 | # External native build folder generated in Android Studio 2.2 and later
65 | .externalNativeBuild
66 | .cxx/
67 |
68 | # Google Services (e.g. APIs or Firebase)
69 | # google-services.json
70 |
71 | # Freeline
72 | freeline.py
73 | freeline/
74 | freeline_project_description.json
75 |
76 | # fastlane
77 | fastlane/report.xml
78 | fastlane/Preview.html
79 | fastlane/screenshots
80 | fastlane/test_output
81 | fastlane/readme.md
82 |
83 | # Version control
84 | vcs.xml
85 |
86 | # lint
87 | lint/intermediates/
88 | lint/generated/
89 | lint/outputs/
90 | lint/tmp/
91 | # lint/reports/
92 |
93 | ### Android Patch ###
94 | gen-external-apklibs
95 | output.json
96 |
97 | # Replacement of .externalNativeBuild directories introduced
98 | # with Android Studio 3.5.
99 |
100 | ### AndroidStudio ###
101 | # Covers files to be ignored for android development using Android Studio.
102 |
103 | # Built application files
104 |
105 | # Files for the ART/Dalvik VM
106 |
107 | # Java class files
108 |
109 | # Generated files
110 |
111 | # Gradle files
112 | .gradle
113 |
114 | # Signing files
115 | .signing/
116 |
117 | # Local configuration file (sdk path, etc)
118 |
119 | # Proguard folder generated by Eclipse
120 |
121 | # Log Files
122 |
123 | # Android Studio
124 | /*/build/
125 | /*/local.properties
126 | /*/out
127 | /*/*/build
128 | /*/*/production
129 | *.ipr
130 | *~
131 | *.swp
132 |
133 | # Keystore files
134 | *.jks
135 | *.keystore
136 |
137 | # Google Services (e.g. APIs or Firebase)
138 | # google-services.json
139 |
140 | # Android Patch
141 |
142 | # External native build folder generated in Android Studio 2.2 and later
143 |
144 | # NDK
145 | obj/
146 |
147 | # IntelliJ IDEA
148 | *.iws
149 | /out/
150 |
151 | # User-specific configurations
152 | .idea/caches/
153 | .idea/libraries/
154 | .idea/shelf/
155 | .idea/.name
156 | .idea/compiler.xml
157 | .idea/copyright/profiles_settings.xml
158 | .idea/encodings.xml
159 | .idea/misc.xml
160 | .idea/scopes/scope_settings.xml
161 | .idea/vcs.xml
162 | .idea/jsLibraryMappings.xml
163 | .idea/datasources.xml
164 | .idea/dataSources.ids
165 | .idea/sqlDataSources.xml
166 | .idea/dynamic.xml
167 | .idea/uiDesigner.xml
168 | .idea/jarRepositories.xml
169 |
170 | # OS-specific files
171 | .DS_Store
172 | .DS_Store?
173 | ._*
174 | .Spotlight-V100
175 | .Trashes
176 | ehthumbs.db
177 | Thumbs.db
178 |
179 | # Legacy Eclipse project files
180 | .classpath
181 | .project
182 | .cproject
183 | .settings/
184 |
185 | # Mobile Tools for Java (J2ME)
186 | .mtj.tmp/
187 |
188 | # Package Files #
189 | *.war
190 | *.ear
191 |
192 | # virtual machine crash logs (Reference: http://www.java.com/en/download/help/error_hotspot.xml)
193 | hs_err_pid*
194 |
195 | ## Plugin-specific files:
196 |
197 | # mpeltonen/sbt-idea plugin
198 | .idea_modules/
199 |
200 | # JIRA plugin
201 | atlassian-ide-plugin.xml
202 |
203 | # Mongo Explorer plugin
204 | .idea/mongoSettings.xml
205 |
206 | # Crashlytics plugin (for Android Studio and IntelliJ)
207 | com_crashlytics_export_strings.xml
208 | crashlytics.properties
209 | crashlytics-build.properties
210 | fabric.properties
211 |
212 | /publish.properties
213 |
214 | ### AndroidStudio Patch ###
215 |
216 | !/gradle/wrapper/gradle-wrapper.jar
217 |
218 | # End of https://www.toptal.com/developers/gitignore/api/android,androidstudio
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
9 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 | xmlns:android
43 |
44 | ^$
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 | xmlns:.*
54 |
55 | ^$
56 |
57 |
58 | BY_NAME
59 |
60 |
61 |
62 |
63 |
64 |
65 | .*:id
66 |
67 | http://schemas.android.com/apk/res/android
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 | .*:name
77 |
78 | http://schemas.android.com/apk/res/android
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 | name
88 |
89 | ^$
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 | style
99 |
100 | ^$
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | .*
110 |
111 | ^$
112 |
113 |
114 | BY_NAME
115 |
116 |
117 |
118 |
119 |
120 |
121 | .*
122 |
123 | http://schemas.android.com/apk/res/android
124 |
125 |
126 | ANDROID_ATTRIBUTE_ORDER
127 |
128 |
129 |
130 |
131 |
132 |
133 | .*
134 |
135 | .*
136 |
137 |
138 | BY_NAME
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 |
--------------------------------------------------------------------------------
/.idea/codeStyles/codeStyleConfig.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2021 onebone
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy
4 | of this software and associated documentation files (the "Software"), to deal
5 | in the Software without restriction, including without limitation the rights
6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 | copies of the Software, and to permit persons to whom the Software is
8 | furnished to do so, subject to the following conditions:
9 |
10 | The above copyright notice and this permission notice shall be included in all
11 | copies or substantial portions of the Software.
12 |
13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
14 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
16 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
17 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
18 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
19 | OR OTHER DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # compose-collapsing-toolbar
2 | A simple implementation of [CollapsingToolbarLayout](https://developer.android.com/reference/com/google/android/material/appbar/CollapsingToolbarLayout) for Jetpack Compose
3 |
4 | ## Installation
5 | You should add `mavenCentral()` repository before installation. Then add the following line to the `dependencies` block in your app level build.gradle:
6 |
7 | ```gradle
8 | implementation "me.onebone:toolbar-compose:2.3.5"
9 | ```
10 | or build.gradle.kts:
11 | ```kotlin
12 | implementation("me.onebone:toolbar-compose:2.3.5")
13 | ```
14 |
15 | ## Example
16 | An example can be found [here](app/src/main).
17 |
18 | ## Usage
19 | ### Using CollapsingToolbarScaffold
20 | `CollapsingToolbarScaffold` is a container to help you place composables and move them as a user dispatches scroll. It provides two holes where you can place you components.
21 | To use `CollapsingToolbarScaffold` you will need `CollapsingToolbarScaffoldState` which could be retrieved using `rememberCollapsingToolbarScaffoldState()`.
22 | ```kotlin
23 | CollapsingToolbarScaffold(
24 | state = rememberCollapsingToolbarScaffoldState(), // provide the state of the scaffold
25 | toolbar = {
26 | // contents of toolbar go here...
27 | }
28 | ) {
29 | // main contents go here...
30 | }
31 | ```
32 |
33 | The toolbar will collapse until it gets as small as the smallest child, and will expand as large as the largest child.
34 |
35 | Also note that the content should be scrollable for the `CollapsingToolbarScaffold` to consume nested scroll. For `LazyColumn`, you don't have to care of anything because it is scrollable by default. Column, however, is not scrollable by default so you can provide `Modifier.verticalScroll()` to make a content dispatch nested scroll.
36 |
37 | ```kotlin
38 | CollapsingToolbarScaffold(
39 | state = rememberCollapsingToolbarScaffoldState(), // provide the state of the scaffold
40 | toolbar = {
41 | // contents of toolbar go here...
42 | }
43 | ) {
44 | Column(
45 | modifier = Modifier
46 | .verticalScroll(rememberScrollState()) // main content should be scrollable for CollapsingToolbarScaffold to consume nested scroll
47 | ) {
48 | // ...
49 | }
50 | }
51 | ```
52 |
53 | By default, `CollapsingToolbar` clips content to its bounds. In order to disable it, set `toolbarClipToBounds = false` in `CollapsingToolbarScaffold`.
54 |
55 | ### CollapsingToolbarScaffoldState
56 | `CollapsingToolbarScaffoldState` is a holder of the scaffold state, such as the value of y offset and how much the toolbar has expanded. The field is public so you may use it as you need.
57 | Note that the `CollapsingToolbarScaffoldState` is stable, which means that a change on a value of the state triggers a recomposition.
58 | ```kotlin
59 | val state = rememberCollapsingToolbarScaffoldState()
60 | val offsetY = state.offsetY // y offset of the layout
61 | val progress = state.toolbarState.progress // how much the toolbar is expanded (0: collapsed, 1: expanded)
62 |
63 | Text(
64 | text = "Hello World",
65 | textSize = (18 + (30 - 18) * progress).sp // text size depending on the progress
66 | // recomposed when the value of the progress is changed
67 | )
68 | ```
69 |
70 | ## parallax, pin, road
71 | You can tell children of CollapsingToolbar how to deal with a collapse/expansion. This works almost the same way to the `collapseMode` in the `CollapsingToolbarLayout` except for the `road` modifier.
72 |
73 | ```kotlin
74 | CollapsingToolbar(/* ... */) {
75 | Image(
76 | modifier = Modifier.parallax(ratio = 0.2f) // parallax, pin, road are available
77 | )
78 | }
79 | ```
80 |
81 | ### road modifier
82 | The `road()` modifier allows you to place a child relatively to the toolbar. It receives two arguments: `whenCollapsed` and `whenExpanded`. As the name suggests, these describe how to place a child when the toolbar is collapsed or expanded, respectively.
83 | This can be used to display a title text on the toolbar which is moving as the scroll is fed.
84 | ```kotlin
85 | CollapsingToolbarScaffold(
86 | toolbar = {
87 | Text(
88 | text = "Title",
89 | modifier = Modifier
90 | .road(
91 | whenCollapsed = Alignment.CenterStart,
92 | whenExpanded = Alignment.BottomEnd
93 | )
94 | )
95 | }
96 | ) {
97 | // ...
98 | }
99 | ```
100 | The above code orders the title `Text` to be placed at the _CenterStart_ position when the toolbar is collapsed and _BottomEnd_ position when it is expanded.
101 |
102 |
103 | ## Scroll Strategy
104 | `ScrollStrategy` defines how CollapsingToolbar consumes scroll. You can set your desired behavior by providing `scrollStrategy` to `CollapsingToolbarScaffold`:
105 |
106 | ```kotlin
107 | CollapsingToolbarScaffold(
108 | /* ... */
109 | scrollStrategy = ScrollStrategy.EnterAlways // EnterAlways, EnterAlwaysCollapsed, ExitUntilCollapsed are available
110 | ) {
111 | /* ... */
112 | }
113 | ```
114 |
115 |
116 | ### ScrollStrategy.EnterAlways
117 | 
118 |
119 | ### ScrollStrategy.EnterAlwaysCollapsed
120 | 
121 |
122 | ### ScrollStrategy.ExitUntilCollapsed
123 | 
124 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.application'
3 | id 'kotlin-android'
4 | }
5 |
6 | android {
7 | compileSdkVersion 33
8 | buildToolsVersion "30.0.3"
9 |
10 | defaultConfig {
11 | applicationId "me.onebone.toolbar"
12 | minSdkVersion 21
13 | targetSdkVersion 33
14 | versionCode 1
15 | versionName "1.0"
16 |
17 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
18 | vectorDrawables {
19 | useSupportLibrary true
20 | }
21 | }
22 |
23 | buildTypes {
24 | release {
25 | minifyEnabled false
26 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
27 | }
28 | }
29 | compileOptions {
30 | sourceCompatibility JavaVersion.VERSION_1_8
31 | targetCompatibility JavaVersion.VERSION_1_8
32 | }
33 | kotlinOptions {
34 | jvmTarget = '1.8'
35 | }
36 | buildFeatures {
37 | compose true
38 | }
39 | composeOptions {
40 | kotlinCompilerExtensionVersion compose_compiler_version
41 | }
42 | }
43 |
44 | dependencies {
45 | implementation 'androidx.core:core-ktx:1.9.0'
46 | implementation 'androidx.appcompat:appcompat:1.6.0'
47 | implementation 'com.google.android.material:material:1.7.0'
48 |
49 | implementation platform('androidx.compose:compose-bom:2023.01.00')
50 | implementation "androidx.compose.ui:ui"
51 | implementation "androidx.compose.material:material"
52 | implementation "androidx.compose.ui:ui-tooling"
53 |
54 | implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.5.1'
55 | implementation 'androidx.activity:activity-compose:1.6.1'
56 |
57 | testImplementation 'junit:junit:4.13.2'
58 | androidTestImplementation 'androidx.test.ext:junit:1.1.5'
59 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
60 |
61 | implementation project(':lib')
62 | }
63 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/me/onebone/toolbar/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package me.onebone.toolbar
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("me.onebone.toolbar", appContext.packageName)
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
12 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/app/src/main/java/me/onebone/toolbar/MainActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2021 onebone
3 | *
4 | * Permission is hereby granted, free of charge, to any person obtaining a copy
5 | * of this software and associated documentation files (the "Software"), to deal
6 | * in the Software without restriction, including without limitation the rights
7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | * copies of the Software, and to permit persons to whom the Software is
9 | * furnished to do so, subject to the following conditions:
10 | *
11 | * The above copyright notice and this permission notice shall be included in all
12 | * copies or substantial portions of the Software.
13 | *
14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 | * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 | * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
20 | * OR OTHER DEALINGS IN THE SOFTWARE.
21 | */
22 |
23 | package me.onebone.toolbar
24 |
25 | import android.os.Bundle
26 | import androidx.activity.ComponentActivity
27 | import androidx.activity.compose.setContent
28 | import androidx.compose.foundation.Image
29 | import androidx.compose.foundation.background
30 | import androidx.compose.foundation.layout.*
31 | import androidx.compose.foundation.lazy.LazyColumn
32 | import androidx.compose.material.MaterialTheme
33 | import androidx.compose.material.Surface
34 | import androidx.compose.material.Text
35 | import androidx.compose.runtime.Composable
36 | import androidx.compose.ui.Alignment
37 | import androidx.compose.ui.Modifier
38 | import androidx.compose.ui.draw.alpha
39 | import androidx.compose.ui.graphics.Color
40 | import androidx.compose.ui.res.painterResource
41 | import androidx.compose.ui.unit.dp
42 | import androidx.compose.ui.unit.sp
43 | import me.onebone.toolbar.ui.theme.CollapsingToolbarTheme
44 |
45 | class MainActivity: ComponentActivity() {
46 | override fun onCreate(savedInstanceState: Bundle?) {
47 | super.onCreate(savedInstanceState)
48 | setContent {
49 | CollapsingToolbarTheme {
50 | // A surface container using the 'background' color from the theme
51 | Surface(color = MaterialTheme.colors.background) {
52 | MainScreen()
53 | }
54 | }
55 | }
56 | }
57 | }
58 |
59 | @Composable
60 | internal fun MainScreen() {
61 | val state = rememberCollapsingToolbarScaffoldState()
62 |
63 | CollapsingToolbarScaffold(
64 | modifier = Modifier
65 | .fillMaxSize(),
66 | state = state,
67 | scrollStrategy = ScrollStrategy.ExitUntilCollapsed,
68 | toolbar = {
69 | val textSize = (18 + (30 - 18) * state.toolbarState.progress).sp
70 |
71 | Box(
72 | modifier = Modifier
73 | .background(MaterialTheme.colors.primary)
74 | .fillMaxWidth()
75 | .height(150.dp)
76 | .pin()
77 | )
78 |
79 | Text(
80 | text = "Title",
81 | modifier = Modifier
82 | .road(Alignment.CenterStart, Alignment.BottomEnd)
83 | .padding(60.dp, 16.dp, 16.dp, 16.dp),
84 | color = Color.White,
85 | fontSize = textSize
86 | )
87 |
88 | Image(
89 | modifier = Modifier
90 | .pin()
91 | .padding(16.dp),
92 | painter = painterResource(id = R.drawable.abc_vector_test),
93 | contentDescription = null
94 | )
95 | }
96 | ) {
97 | LazyColumn(
98 | modifier = Modifier
99 | .fillMaxWidth()
100 | ) {
101 | items(100) {
102 | Text(
103 | text = "Item $it",
104 | modifier = Modifier.padding(8.dp)
105 | )
106 | }
107 | }
108 |
109 | Box(
110 | modifier = Modifier
111 | .fillMaxWidth()
112 | .alpha(0.5f)
113 | .background(MaterialTheme.colors.secondary)
114 | .height(40.dp)
115 | )
116 | }
117 |
118 | CollapsingToolbarScaffold(
119 | modifier = Modifier.fillMaxSize(),
120 | state = rememberCollapsingToolbarScaffoldState(),
121 | scrollStrategy = ScrollStrategy.ExitUntilCollapsed,
122 | toolbar = {
123 | // toolbar contents...
124 | }
125 | ) {
126 | // body contents...
127 | }
128 | }
129 |
--------------------------------------------------------------------------------
/app/src/main/java/me/onebone/toolbar/ParallaxActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2021 onebone
3 | *
4 | * Permission is hereby granted, free of charge, to any person obtaining a copy
5 | * of this software and associated documentation files (the "Software"), to deal
6 | * in the Software without restriction, including without limitation the rights
7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | * copies of the Software, and to permit persons to whom the Software is
9 | * furnished to do so, subject to the following conditions:
10 | *
11 | * The above copyright notice and this permission notice shall be included in all
12 | * copies or substantial portions of the Software.
13 | *
14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 | * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 | * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
20 | * OR OTHER DEALINGS IN THE SOFTWARE.
21 | */
22 |
23 | package me.onebone.toolbar
24 |
25 | import android.os.Bundle
26 | import androidx.activity.ComponentActivity
27 | import androidx.activity.compose.setContent
28 | import androidx.compose.foundation.Image
29 | import androidx.compose.foundation.background
30 | import androidx.compose.foundation.layout.Box
31 | import androidx.compose.foundation.layout.Row
32 | import androidx.compose.foundation.layout.Spacer
33 | import androidx.compose.foundation.layout.fillMaxSize
34 | import androidx.compose.foundation.layout.fillMaxWidth
35 | import androidx.compose.foundation.layout.height
36 | import androidx.compose.foundation.layout.padding
37 | import androidx.compose.foundation.lazy.LazyColumn
38 | import androidx.compose.foundation.lazy.items
39 | import androidx.compose.material.Button
40 | import androidx.compose.material.Checkbox
41 | import androidx.compose.material.MaterialTheme
42 | import androidx.compose.material.Surface
43 | import androidx.compose.material.Text
44 | import androidx.compose.runtime.Composable
45 | import androidx.compose.runtime.getValue
46 | import androidx.compose.runtime.mutableStateOf
47 | import androidx.compose.runtime.remember
48 | import androidx.compose.runtime.setValue
49 | import androidx.compose.ui.Alignment
50 | import androidx.compose.ui.Modifier
51 | import androidx.compose.ui.graphics.graphicsLayer
52 | import androidx.compose.ui.layout.ContentScale
53 | import androidx.compose.ui.res.painterResource
54 | import androidx.compose.ui.text.font.FontWeight
55 | import androidx.compose.ui.unit.dp
56 | import me.onebone.toolbar.ui.theme.CollapsingToolbarTheme
57 |
58 | class ParallaxActivity: ComponentActivity() {
59 | override fun onCreate(savedInstanceState: Bundle?) {
60 | super.onCreate(savedInstanceState)
61 | setContent {
62 | CollapsingToolbarTheme {
63 | Surface(color = MaterialTheme.colors.background) {
64 | ParallaxEffect()
65 | }
66 | }
67 | }
68 | }
69 | }
70 |
71 | @Composable
72 | fun ParallaxEffect() {
73 | val state = rememberCollapsingToolbarScaffoldState()
74 |
75 | var enabled by remember { mutableStateOf(true) }
76 |
77 | Box {
78 | CollapsingToolbarScaffold(
79 | modifier = Modifier.fillMaxSize(),
80 | state = state,
81 | scrollStrategy = ScrollStrategy.EnterAlwaysCollapsed,
82 | toolbarModifier = Modifier.background(MaterialTheme.colors.primary),
83 | enabled = enabled,
84 | toolbar = {
85 | // Collapsing toolbar collapses its size as small as the that of
86 | // a smallest child. To make the toolbar collapse to 50dp, we create
87 | // a dummy Spacer composable.
88 | // You may replace it with TopAppBar or other preferred composable.
89 | Spacer(
90 | modifier = Modifier
91 | .fillMaxWidth()
92 | .height(50.dp)
93 | )
94 |
95 | Image(
96 | painter = painterResource(id = R.drawable.android),
97 | modifier = Modifier
98 | .parallax(0.5f)
99 | .height(300.dp)
100 | .graphicsLayer {
101 | // change alpha of Image as the toolbar expands
102 | alpha = state.toolbarState.progress
103 | },
104 | contentScale = ContentScale.Crop,
105 | contentDescription = null
106 | )
107 | }
108 | ) {
109 | LazyColumn(
110 | modifier = Modifier
111 | .fillMaxSize()
112 | ) {
113 | items(
114 | List(100) { "Hello World!! $it" }
115 | ) {
116 | Text(
117 | text = it,
118 | modifier = Modifier
119 | .fillMaxWidth()
120 | .padding(4.dp)
121 | )
122 | }
123 | }
124 |
125 | @OptIn(ExperimentalToolbarApi::class)
126 | Button(
127 | modifier = Modifier
128 | .padding(16.dp)
129 | .align(Alignment.BottomEnd),
130 | onClick = { }
131 | ) {
132 | Text(text = "Floating Button!")
133 | }
134 | }
135 |
136 | Row(
137 | verticalAlignment = Alignment.CenterVertically
138 | ) {
139 | Checkbox(checked = enabled, onCheckedChange = { enabled = !enabled })
140 |
141 | Text("Enable collapse/expand", fontWeight = FontWeight.Bold)
142 | }
143 | }
144 | }
145 |
--------------------------------------------------------------------------------
/app/src/main/java/me/onebone/toolbar/ui/theme/Color.kt:
--------------------------------------------------------------------------------
1 | package me.onebone.toolbar.ui.theme
2 |
3 | import androidx.compose.ui.graphics.Color
4 |
5 | val Purple200 = Color(0xFFBB86FC)
6 | val Purple500 = Color(0xFF6200EE)
7 | val Purple700 = Color(0xFF3700B3)
8 | val Teal200 = Color(0xFF03DAC5)
--------------------------------------------------------------------------------
/app/src/main/java/me/onebone/toolbar/ui/theme/Shape.kt:
--------------------------------------------------------------------------------
1 | package me.onebone.toolbar.ui.theme
2 |
3 | import androidx.compose.foundation.shape.RoundedCornerShape
4 | import androidx.compose.material.Shapes
5 | import androidx.compose.ui.unit.dp
6 |
7 | val Shapes = Shapes(
8 | small = RoundedCornerShape(4.dp),
9 | medium = RoundedCornerShape(4.dp),
10 | large = RoundedCornerShape(0.dp)
11 | )
--------------------------------------------------------------------------------
/app/src/main/java/me/onebone/toolbar/ui/theme/Theme.kt:
--------------------------------------------------------------------------------
1 | package me.onebone.toolbar.ui.theme
2 |
3 | import androidx.compose.foundation.isSystemInDarkTheme
4 | import androidx.compose.material.MaterialTheme
5 | import androidx.compose.material.darkColors
6 | import androidx.compose.material.lightColors
7 | import androidx.compose.runtime.Composable
8 |
9 | private val DarkColorPalette = darkColors(
10 | primary = Purple200,
11 | primaryVariant = Purple700,
12 | secondary = Teal200
13 | )
14 |
15 | private val LightColorPalette = lightColors(
16 | primary = Purple500,
17 | primaryVariant = Purple700,
18 | secondary = Teal200
19 |
20 | /* Other default colors to override
21 | background = Color.White,
22 | surface = Color.White,
23 | onPrimary = Color.White,
24 | onSecondary = Color.Black,
25 | onBackground = Color.Black,
26 | onSurface = Color.Black,
27 | */
28 | )
29 |
30 | @Composable
31 | fun CollapsingToolbarTheme(
32 | darkTheme: Boolean = isSystemInDarkTheme(),
33 | content: @Composable () -> Unit
34 | ) {
35 | val colors = if (darkTheme) {
36 | DarkColorPalette
37 | } else {
38 | LightColorPalette
39 | }
40 |
41 | MaterialTheme(
42 | colors = colors,
43 | typography = Typography,
44 | shapes = Shapes,
45 | content = content
46 | )
47 | }
48 |
--------------------------------------------------------------------------------
/app/src/main/java/me/onebone/toolbar/ui/theme/Type.kt:
--------------------------------------------------------------------------------
1 | package me.onebone.toolbar.ui.theme
2 |
3 | import androidx.compose.material.Typography
4 | import androidx.compose.ui.text.TextStyle
5 | import androidx.compose.ui.text.font.FontFamily
6 | import androidx.compose.ui.text.font.FontWeight
7 | import androidx.compose.ui.unit.sp
8 |
9 | // Set of Material typography styles to start with
10 | val Typography = Typography(
11 | body1 = TextStyle(
12 | fontFamily = FontFamily.Default,
13 | fontWeight = FontWeight.Normal,
14 | fontSize = 16.sp
15 | )
16 | /* Other default text styles to override
17 | button = TextStyle(
18 | fontFamily = FontFamily.Default,
19 | fontWeight = FontWeight.W500,
20 | fontSize = 14.sp
21 | ),
22 | caption = TextStyle(
23 | fontFamily = FontFamily.Default,
24 | fontWeight = FontWeight.Normal,
25 | fontSize = 12.sp
26 | )
27 | */
28 | )
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
31 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/android.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/onebone/compose-collapsing-toolbar/5fefd2134c906bd649162b938ae6883a785e33e9/app/src/main/res/drawable/android.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/onebone/compose-collapsing-toolbar/5fefd2134c906bd649162b938ae6883a785e33e9/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/onebone/compose-collapsing-toolbar/5fefd2134c906bd649162b938ae6883a785e33e9/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/onebone/compose-collapsing-toolbar/5fefd2134c906bd649162b938ae6883a785e33e9/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/onebone/compose-collapsing-toolbar/5fefd2134c906bd649162b938ae6883a785e33e9/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/onebone/compose-collapsing-toolbar/5fefd2134c906bd649162b938ae6883a785e33e9/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/onebone/compose-collapsing-toolbar/5fefd2134c906bd649162b938ae6883a785e33e9/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/onebone/compose-collapsing-toolbar/5fefd2134c906bd649162b938ae6883a785e33e9/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/onebone/compose-collapsing-toolbar/5fefd2134c906bd649162b938ae6883a785e33e9/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/onebone/compose-collapsing-toolbar/5fefd2134c906bd649162b938ae6883a785e33e9/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/onebone/compose-collapsing-toolbar/5fefd2134c906bd649162b938ae6883a785e33e9/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/values-night/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
17 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
11 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Collapsing Toolbar
3 | MainActivity
4 | ParallaxActivity
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
17 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/app/src/test/java/me/onebone/toolbar/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package me.onebone.toolbar
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 | buildscript {
3 | ext {
4 | library_version = '2.3.5'
5 |
6 | kotlin_version = '1.7.20'
7 | compose_compiler_version = '1.3.2'
8 | }
9 |
10 | repositories {
11 | google()
12 | mavenCentral()
13 | }
14 | dependencies {
15 | classpath 'com.android.tools.build:gradle:7.3.1'
16 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
17 |
18 | // NOTE: Do not place your application dependencies here; they belong
19 | // in the individual module build.gradle files
20 | }
21 | }
22 |
23 | allprojects {
24 | repositories {
25 | google()
26 | mavenCentral()
27 | }
28 | }
29 |
30 | task clean(type: Delete) {
31 | delete rootProject.buildDir
32 | }
33 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app"s APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
20 | # Kotlin code style for this project: "official" or "obsolete":
21 | kotlin.code.style=official
22 |
--------------------------------------------------------------------------------
/gradle/publish.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'maven-publish'
2 | apply plugin: 'signing'
3 |
4 | ext['signing.keyId'] = ''
5 | ext['signing.password'] = ''
6 | ext['signing.secretKeyRingFile'] = ''
7 | ext['ossrhUsername'] = ''
8 | ext['ossrhPassword'] = ''
9 |
10 | var properties = new Properties()
11 | var file = project.rootProject.file('publish.properties')
12 | if(file.exists()) {
13 | properties.load(new FileInputStream(file))
14 |
15 | ext['signing.keyId'] = properties.getProperty('signing.keyId')
16 | ext['signing.password'] = properties.getProperty('signing.password')
17 | ext['signing.secretKeyRingFile'] = properties.getProperty('signing.secretKeyRingFile')
18 |
19 | ext.ossrhUsername = properties.getProperty('ossrhUsername')
20 | ext.ossrhPassword = properties.getProperty('ossrhPassword')
21 | }
22 |
23 | afterEvaluate {
24 | publishing {
25 | publications {
26 | release(MavenPublication) {
27 | groupId = 'me.onebone'
28 | artifactId = 'toolbar-compose'
29 | version = rootProject.ext.library_version
30 |
31 | from components.release
32 |
33 | artifact androidSourceSets
34 |
35 | pom {
36 | name = 'Collapsing Toolbar'
37 | description = 'A simple implementation of collapsing toolbar for Jetpack Compose'
38 | url = 'https://github.com/onebone/compose-collapsing-toolbar'
39 |
40 | licenses {
41 | license {
42 | name = 'MIT License'
43 | url = 'https://opensource.org/licenses/MIT'
44 | }
45 | }
46 |
47 | developers {
48 | developer {
49 | id = 'onebone'
50 | name = 'onebone'
51 | email = 'me@onebone.me'
52 | }
53 | }
54 |
55 | scm {
56 | connection = 'scm:git:git://github.com/onebone/compose-collapsing-toolbar.git'
57 | developerConnection = 'scm:git:ssh://github.com/onebone/compose-collapsing-toolbar.git'
58 | url = 'https://github.com/onebone/compose-collapsing-toolbar'
59 | }
60 | }
61 | }
62 | }
63 |
64 | repositories {
65 | maven {
66 | name = 'mavenCentral'
67 | url = version.endsWith('SNAPSHOT') ?
68 | 'https://s01.oss.sonatype.org/content/repositories/snapshots/' :
69 | 'https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/'
70 |
71 | credentials {
72 | username = ossrhUsername
73 | password = ossrhPassword
74 | }
75 | }
76 | }
77 | }
78 | }
79 |
80 | task androidSourceSets(type: Jar) {
81 | archiveClassifier.set('sources')
82 |
83 | from android.sourceSets.main.java.srcDirs
84 | from android.sourceSets.main.kotlin.srcDirs
85 | }
86 |
87 | artifacts {
88 | archives androidSourceSets
89 | }
90 |
91 | signing {
92 | sign publishing.publications
93 | }
94 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/onebone/compose-collapsing-toolbar/5fefd2134c906bd649162b938ae6883a785e33e9/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu Apr 29 12:35:18 KST 2021
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/img/enter-always-collapsed.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/onebone/compose-collapsing-toolbar/5fefd2134c906bd649162b938ae6883a785e33e9/img/enter-always-collapsed.gif
--------------------------------------------------------------------------------
/img/enter-always.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/onebone/compose-collapsing-toolbar/5fefd2134c906bd649162b938ae6883a785e33e9/img/enter-always.gif
--------------------------------------------------------------------------------
/img/exit-until-collapsed.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/onebone/compose-collapsing-toolbar/5fefd2134c906bd649162b938ae6883a785e33e9/img/exit-until-collapsed.gif
--------------------------------------------------------------------------------
/lib/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/lib/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.library'
3 | id 'kotlin-android'
4 | }
5 |
6 | android {
7 | namespace 'me.onebone.toolbar'
8 |
9 | compileSdkVersion 33
10 | buildToolsVersion "30.0.3"
11 |
12 | defaultConfig {
13 | minSdkVersion 21
14 | targetSdkVersion 33
15 |
16 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
17 | consumerProguardFiles "consumer-rules.pro"
18 | }
19 |
20 | buildTypes {
21 | release {
22 | minifyEnabled false
23 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
24 | }
25 | }
26 | compileOptions {
27 | sourceCompatibility JavaVersion.VERSION_1_8
28 | targetCompatibility JavaVersion.VERSION_1_8
29 | }
30 | kotlinOptions {
31 | jvmTarget = '1.8'
32 | }
33 |
34 | buildFeatures {
35 | compose = true
36 | }
37 |
38 | composeOptions {
39 | kotlinCompilerExtensionVersion "$compose_compiler_version"
40 | }
41 |
42 | packagingOptions {
43 | exclude "META-INF/AL2.0"
44 | exclude "META-INF/LGPL2.1"
45 | }
46 | }
47 |
48 | dependencies {
49 | testImplementation 'junit:junit:4.13.2'
50 | androidTestImplementation 'androidx.test.ext:junit:1.1.5'
51 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
52 |
53 | implementation platform('androidx.compose:compose-bom:2023.01.00')
54 |
55 | implementation "androidx.compose.ui:ui"
56 | implementation "androidx.compose.foundation:foundation"
57 | implementation "androidx.compose.ui:ui-tooling"
58 | androidTestImplementation "androidx.compose.ui:ui-test-junit4"
59 | }
60 |
61 | apply from: rootProject.file('gradle/publish.gradle')
62 |
--------------------------------------------------------------------------------
/lib/consumer-rules.pro:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/onebone/compose-collapsing-toolbar/5fefd2134c906bd649162b938ae6883a785e33e9/lib/consumer-rules.pro
--------------------------------------------------------------------------------
/lib/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/lib/src/androidTest/java/me/onebone/toolbar/CollapsingToolbarTest.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2021 onebone
3 | *
4 | * Permission is hereby granted, free of charge, to any person obtaining a copy
5 | * of this software and associated documentation files (the "Software"), to deal
6 | * in the Software without restriction, including without limitation the rights
7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | * copies of the Software, and to permit persons to whom the Software is
9 | * furnished to do so, subject to the following conditions:
10 | *
11 | * The above copyright notice and this permission notice shall be included in all
12 | * copies or substantial portions of the Software.
13 | *
14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 | * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 | * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
20 | * OR OTHER DEALINGS IN THE SOFTWARE.
21 | */
22 |
23 | package me.onebone.toolbar
24 |
25 | import androidx.compose.foundation.layout.Box
26 | import androidx.compose.foundation.layout.fillMaxSize
27 | import androidx.compose.foundation.layout.fillMaxWidth
28 | import androidx.compose.foundation.layout.height
29 | import androidx.compose.foundation.lazy.LazyColumn
30 | import androidx.compose.foundation.lazy.items
31 | import androidx.compose.material.Text
32 | import androidx.compose.ui.Modifier
33 | import androidx.compose.ui.semantics.semantics
34 | import androidx.compose.ui.semantics.testTag
35 | import androidx.compose.ui.test.assertHeightIsEqualTo
36 | import androidx.compose.ui.test.hasTestTag
37 | import androidx.compose.ui.test.junit4.createComposeRule
38 | import androidx.compose.ui.test.performTouchInput
39 | import androidx.compose.ui.test.swipeUp
40 | import androidx.compose.ui.unit.dp
41 | import androidx.test.ext.junit.runners.AndroidJUnit4
42 | import kotlin.math.abs
43 | import org.junit.Rule
44 | import org.junit.Test
45 | import org.junit.runner.RunWith
46 |
47 | @RunWith(AndroidJUnit4::class)
48 | class CollapsingToolbarTest {
49 | @get:Rule
50 | val rule = createComposeRule()
51 |
52 | @Test
53 | fun testCollapse() {
54 | val state = CollapsingToolbarScaffoldState(
55 | CollapsingToolbarState()
56 | )
57 |
58 | rule.setContent {
59 | CollapsingToolbarScaffold(
60 | modifier = Modifier
61 | .fillMaxSize(),
62 | state = state,
63 | scrollStrategy = ScrollStrategy.ExitUntilCollapsed,
64 | toolbarModifier = Modifier
65 | .semantics {
66 | testTag = "toolbar"
67 | },
68 | toolbar = {
69 | Box(modifier = Modifier
70 | .fillMaxWidth()
71 | .height(300.dp))
72 | Box(modifier = Modifier
73 | .fillMaxWidth()
74 | .height(50.dp))
75 | }
76 | ) {
77 | LazyColumn(modifier = Modifier
78 | .fillMaxSize()
79 | .semantics {
80 | testTag = "contentList"
81 | }
82 | ) {
83 | items(List(100) { "Hello $it" }) {
84 | Text(text = it)
85 | }
86 | }
87 | }
88 | }
89 |
90 | assert(state.toolbarState.progress == 1f)
91 |
92 | rule.onNode(hasTestTag("toolbar"))
93 | .assertHeightIsEqualTo(300.dp)
94 |
95 | rule.onNode(hasTestTag("contentList"))
96 | .performTouchInput {
97 | swipeUp()
98 | }
99 |
100 | rule.onNode(hasTestTag("toolbar"))
101 | .assertHeightIsEqualTo(50.dp)
102 |
103 | assert(abs(state.toolbarState.progress) < 0.01f)
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/lib/src/androidTest/java/me/onebone/toolbar/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package me.onebone.toolbar
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("me.onebone.toolbar.test", appContext.packageName)
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/lib/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/lib/src/main/java/me/onebone/toolbar/Annotations.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2021 onebone
3 | *
4 | * Permission is hereby granted, free of charge, to any person obtaining a copy
5 | * of this software and associated documentation files (the "Software"), to deal
6 | * in the Software without restriction, including without limitation the rights
7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | * copies of the Software, and to permit persons to whom the Software is
9 | * furnished to do so, subject to the following conditions:
10 | *
11 | * The above copyright notice and this permission notice shall be included in all
12 | * copies or substantial portions of the Software.
13 | *
14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 | * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 | * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
20 | * OR OTHER DEALINGS IN THE SOFTWARE.
21 | */
22 |
23 | package me.onebone.toolbar
24 |
25 | @RequiresOptIn(
26 | message = "This is an experimental API of compose-collapsing-toolbar. Any declarations with " +
27 | "the annotation might be removed or changed in some way without any notice.",
28 | level = RequiresOptIn.Level.WARNING
29 | )
30 | @Target(
31 | AnnotationTarget.FUNCTION,
32 | AnnotationTarget.PROPERTY,
33 | AnnotationTarget.CLASS
34 | )
35 | @Retention(AnnotationRetention.BINARY)
36 | annotation class ExperimentalToolbarApi
37 |
--------------------------------------------------------------------------------
/lib/src/main/java/me/onebone/toolbar/AppBarContainer.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2021 onebone
3 | *
4 | * Permission is hereby granted, free of charge, to any person obtaining a copy
5 | * of this software and associated documentation files (the "Software"), to deal
6 | * in the Software without restriction, including without limitation the rights
7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | * copies of the Software, and to permit persons to whom the Software is
9 | * furnished to do so, subject to the following conditions:
10 | *
11 | * The above copyright notice and this permission notice shall be included in all
12 | * copies or substantial portions of the Software.
13 | *
14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 | * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 | * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
20 | * OR OTHER DEALINGS IN THE SOFTWARE.
21 | */
22 |
23 | package me.onebone.toolbar
24 |
25 | import androidx.compose.foundation.gestures.ScrollableDefaults
26 | import androidx.compose.runtime.Composable
27 | import androidx.compose.runtime.State
28 | import androidx.compose.runtime.mutableStateOf
29 | import androidx.compose.runtime.remember
30 | import androidx.compose.ui.Modifier
31 | import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
32 | import androidx.compose.ui.input.nestedscroll.nestedScroll
33 | import androidx.compose.ui.layout.Layout
34 | import androidx.compose.ui.layout.Measurable
35 | import androidx.compose.ui.layout.MeasurePolicy
36 | import androidx.compose.ui.layout.MeasureResult
37 | import androidx.compose.ui.layout.MeasureScope
38 | import androidx.compose.ui.layout.ParentDataModifier
39 | import androidx.compose.ui.layout.Placeable
40 | import androidx.compose.ui.unit.Constraints
41 | import androidx.compose.ui.unit.Density
42 | import kotlin.math.max
43 | import kotlin.math.roundToInt
44 |
45 | @Deprecated(
46 | "Use AppBarContainer for naming consistency",
47 | replaceWith = ReplaceWith(
48 | "AppBarContainer(modifier, scrollStrategy, collapsingToolbarState, content)",
49 | "me.onebone.toolbar"
50 | )
51 | )
52 | @Composable
53 | fun AppbarContainer(
54 | modifier: Modifier = Modifier,
55 | scrollStrategy: ScrollStrategy,
56 | collapsingToolbarState: CollapsingToolbarState,
57 | content: @Composable AppbarContainerScope.() -> Unit
58 | ) {
59 | AppBarContainer(
60 | modifier = modifier,
61 | scrollStrategy = scrollStrategy,
62 | collapsingToolbarState = collapsingToolbarState,
63 | content = content
64 | )
65 | }
66 |
67 | @Deprecated(
68 | "AppBarContainer is replaced with CollapsingToolbarScaffold",
69 | replaceWith = ReplaceWith(
70 | "CollapsingToolbarScaffold",
71 | "me.onebone.toolbar"
72 | )
73 | )
74 | @Composable
75 | fun AppBarContainer(
76 | modifier: Modifier = Modifier,
77 | scrollStrategy: ScrollStrategy,
78 | /** The state of a connected collapsing toolbar */
79 | collapsingToolbarState: CollapsingToolbarState,
80 | content: @Composable AppbarContainerScope.() -> Unit
81 | ) {
82 | val offsetY = remember { mutableStateOf(0) }
83 | val flingBehavior = ScrollableDefaults.flingBehavior()
84 |
85 | val (scope, measurePolicy) = remember(scrollStrategy, collapsingToolbarState) {
86 | AppbarContainerScopeImpl(scrollStrategy.create(offsetY, collapsingToolbarState, flingBehavior)) to
87 | AppbarMeasurePolicy(scrollStrategy, collapsingToolbarState, offsetY)
88 | }
89 |
90 | Layout(
91 | content = { scope.content() },
92 | measurePolicy = measurePolicy,
93 | modifier = modifier
94 | )
95 | }
96 |
97 | interface AppbarContainerScope {
98 | fun Modifier.appBarBody(): Modifier
99 | }
100 |
101 | internal class AppbarContainerScopeImpl(
102 | private val nestedScrollConnection: NestedScrollConnection
103 | ): AppbarContainerScope {
104 | override fun Modifier.appBarBody(): Modifier {
105 | return this
106 | .then(AppBarBodyMarkerModifier)
107 | .nestedScroll(nestedScrollConnection)
108 | }
109 | }
110 |
111 | private object AppBarBodyMarkerModifier: ParentDataModifier {
112 | override fun Density.modifyParentData(parentData: Any?): Any {
113 | return AppBarBodyMarker
114 | }
115 | }
116 |
117 | private object AppBarBodyMarker
118 |
119 | private class AppbarMeasurePolicy(
120 | private val scrollStrategy: ScrollStrategy,
121 | private val toolbarState: CollapsingToolbarState,
122 | private val offsetY: State
123 | ): MeasurePolicy {
124 | override fun MeasureScope.measure(
125 | measurables: List,
126 | constraints: Constraints
127 | ): MeasureResult {
128 | var width = 0
129 | var height = 0
130 |
131 | var toolbarPlaceable: Placeable? = null
132 |
133 | val nonToolbars = measurables.filter {
134 | val data = it.parentData
135 | if(data != AppBarBodyMarker) {
136 | if(toolbarPlaceable != null)
137 | throw IllegalStateException("There cannot exist multiple toolbars under single parent")
138 |
139 | val placeable = it.measure(constraints.copy(
140 | minWidth = 0,
141 | minHeight = 0
142 | ))
143 | width = max(width, placeable.width)
144 | height = max(height, placeable.height)
145 |
146 | toolbarPlaceable = placeable
147 |
148 | false
149 | }else{
150 | true
151 | }
152 | }
153 |
154 | val placeables = nonToolbars.map { measurable ->
155 | val childConstraints = if(scrollStrategy == ScrollStrategy.ExitUntilCollapsed) {
156 | constraints.copy(
157 | minWidth = 0,
158 | minHeight = 0,
159 | maxHeight = max(0, constraints.maxHeight - toolbarState.minHeight)
160 | )
161 | }else{
162 | constraints.copy(
163 | minWidth = 0,
164 | minHeight = 0
165 | )
166 | }
167 |
168 | val placeable = measurable.measure(childConstraints)
169 |
170 | width = max(width, placeable.width)
171 | height = max(height, placeable.height)
172 |
173 | placeable
174 | }
175 |
176 | height += (toolbarPlaceable?.height ?: 0)
177 |
178 | return layout(
179 | width.coerceIn(constraints.minWidth, constraints.maxWidth),
180 | height.coerceIn(constraints.minHeight, constraints.maxHeight)
181 | ) {
182 | toolbarPlaceable?.place(x = 0, y = offsetY.value)
183 |
184 | placeables.forEach { placeable ->
185 | placeable.place(
186 | x = 0,
187 | y = offsetY.value + (toolbarPlaceable?.height ?: 0)
188 | )
189 | }
190 | }
191 | }
192 | }
193 |
--------------------------------------------------------------------------------
/lib/src/main/java/me/onebone/toolbar/CollapsingToolbar.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2021 onebone
3 | *
4 | * Permission is hereby granted, free of charge, to any person obtaining a copy
5 | * of this software and associated documentation files (the "Software"), to deal
6 | * in the Software without restriction, including without limitation the rights
7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | * copies of the Software, and to permit persons to whom the Software is
9 | * furnished to do so, subject to the following conditions:
10 | *
11 | * The above copyright notice and this permission notice shall be included in all
12 | * copies or substantial portions of the Software.
13 | *
14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 | * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 | * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
20 | * OR OTHER DEALINGS IN THE SOFTWARE.
21 | */
22 |
23 | package me.onebone.toolbar
24 |
25 | import androidx.annotation.FloatRange
26 | import androidx.compose.animation.core.AnimationState
27 | import androidx.compose.animation.core.animateTo
28 | import androidx.compose.animation.core.tween
29 | import androidx.compose.foundation.MutatePriority
30 | import androidx.compose.foundation.gestures.FlingBehavior
31 | import androidx.compose.foundation.gestures.ScrollScope
32 | import androidx.compose.foundation.gestures.ScrollableState
33 | import androidx.compose.runtime.Composable
34 | import androidx.compose.runtime.Stable
35 | import androidx.compose.runtime.getValue
36 | import androidx.compose.runtime.mutableStateOf
37 | import androidx.compose.runtime.remember
38 | import androidx.compose.runtime.setValue
39 | import androidx.compose.ui.Alignment
40 | import androidx.compose.ui.Modifier
41 | import androidx.compose.ui.draw.clipToBounds
42 | import androidx.compose.ui.layout.Layout
43 | import androidx.compose.ui.layout.Measurable
44 | import androidx.compose.ui.layout.MeasurePolicy
45 | import androidx.compose.ui.layout.MeasureResult
46 | import androidx.compose.ui.layout.MeasureScope
47 | import androidx.compose.ui.layout.ParentDataModifier
48 | import androidx.compose.ui.unit.Constraints
49 | import androidx.compose.ui.unit.Density
50 | import androidx.compose.ui.unit.IntSize
51 | import kotlin.math.absoluteValue
52 | import kotlin.math.max
53 | import kotlin.math.min
54 | import kotlin.math.roundToInt
55 |
56 | @Stable
57 | class CollapsingToolbarState(
58 | initial: Int = Int.MAX_VALUE
59 | ): ScrollableState {
60 | /**
61 | * [height] indicates current height of the toolbar.
62 | */
63 | var height: Int by mutableStateOf(initial)
64 | private set
65 |
66 | /**
67 | * [minHeight] indicates the minimum height of the collapsing toolbar. The toolbar
68 | * may collapse its height to [minHeight] but not smaller. This size is determined by
69 | * the smallest child.
70 | */
71 | var minHeight: Int
72 | get() = minHeightState
73 | internal set(value) {
74 | minHeightState = value
75 |
76 | if(height < value) {
77 | height = value
78 | }
79 | }
80 |
81 | /**
82 | * [maxHeight] indicates the maximum height of the collapsing toolbar. The toolbar
83 | * may expand its height to [maxHeight] but not larger. This size is determined by
84 | * the largest child.
85 | */
86 | var maxHeight: Int
87 | get() = maxHeightState
88 | internal set(value) {
89 | maxHeightState = value
90 |
91 | if(value < height) {
92 | height = value
93 | }
94 | }
95 |
96 | private var maxHeightState by mutableStateOf(Int.MAX_VALUE)
97 | private var minHeightState by mutableStateOf(0)
98 |
99 | val progress: Float
100 | @FloatRange(from = 0.0, to = 1.0)
101 | get() =
102 | if(minHeight == maxHeight) {
103 | 0f
104 | }else{
105 | ((height - minHeight).toFloat() / (maxHeight - minHeight)).coerceIn(0f, 1f)
106 | }
107 |
108 | private val scrollableState = ScrollableState { value ->
109 | val consume = if(value < 0) {
110 | max(minHeight.toFloat() - height, value)
111 | }else{
112 | min(maxHeight.toFloat() - height, value)
113 | }
114 |
115 | val current = consume + deferredConsumption
116 | val currentInt = current.toInt()
117 |
118 | if(current.absoluteValue > 0) {
119 | height += currentInt
120 | deferredConsumption = current - currentInt
121 | }
122 |
123 | consume
124 | }
125 |
126 | private var deferredConsumption: Float = 0f
127 |
128 | /**
129 | * @return consumed scroll value is returned
130 | */
131 | @Deprecated(
132 | message = "feedScroll() is deprecated, use dispatchRawDelta() instead.",
133 | replaceWith = ReplaceWith("dispatchRawDelta(value)")
134 | )
135 | fun feedScroll(value: Float): Float = dispatchRawDelta(value)
136 |
137 | @ExperimentalToolbarApi
138 | suspend fun expand(duration: Int = 200) {
139 | val anim = AnimationState(height.toFloat())
140 |
141 | scroll {
142 | var prev = anim.value
143 | anim.animateTo(maxHeight.toFloat(), tween(duration)) {
144 | scrollBy(value - prev)
145 | prev = value
146 | }
147 | }
148 | }
149 |
150 | @ExperimentalToolbarApi
151 | suspend fun collapse(duration: Int = 200) {
152 | val anim = AnimationState(height.toFloat())
153 |
154 | scroll {
155 | var prev = anim.value
156 | anim.animateTo(minHeight.toFloat(), tween(duration)) {
157 | scrollBy(value - prev)
158 | prev = value
159 | }
160 | }
161 | }
162 |
163 | /**
164 | * @return Remaining velocity after fling
165 | */
166 | suspend fun fling(flingBehavior: FlingBehavior, velocity: Float): Float {
167 | var left = velocity
168 | scroll {
169 | with(flingBehavior) {
170 | left = performFling(left)
171 | }
172 | }
173 |
174 | return left
175 | }
176 |
177 | override val isScrollInProgress: Boolean
178 | get() = scrollableState.isScrollInProgress
179 |
180 | override fun dispatchRawDelta(delta: Float): Float = scrollableState.dispatchRawDelta(delta)
181 |
182 | override suspend fun scroll(
183 | scrollPriority: MutatePriority,
184 | block: suspend ScrollScope.() -> Unit
185 | ) = scrollableState.scroll(scrollPriority, block)
186 | }
187 |
188 | @Composable
189 | fun rememberCollapsingToolbarState(
190 | initial: Int = Int.MAX_VALUE
191 | ): CollapsingToolbarState {
192 | return remember {
193 | CollapsingToolbarState(
194 | initial = initial
195 | )
196 | }
197 | }
198 |
199 | @Composable
200 | fun CollapsingToolbar(
201 | modifier: Modifier = Modifier,
202 | clipToBounds: Boolean = true,
203 | collapsingToolbarState: CollapsingToolbarState,
204 | content: @Composable CollapsingToolbarScope.() -> Unit
205 | ) {
206 | val measurePolicy = remember(collapsingToolbarState) {
207 | CollapsingToolbarMeasurePolicy(collapsingToolbarState)
208 | }
209 |
210 | Layout(
211 | content = { CollapsingToolbarScopeInstance.content() },
212 | measurePolicy = measurePolicy,
213 | modifier = modifier.then(
214 | if (clipToBounds) {
215 | Modifier.clipToBounds()
216 | } else {
217 | Modifier
218 | }
219 | )
220 | )
221 | }
222 |
223 | private class CollapsingToolbarMeasurePolicy(
224 | private val collapsingToolbarState: CollapsingToolbarState
225 | ): MeasurePolicy {
226 | override fun MeasureScope.measure(
227 | measurables: List,
228 | constraints: Constraints
229 | ): MeasureResult {
230 | val placeables = measurables.map {
231 | it.measure(
232 | constraints.copy(
233 | minWidth = 0,
234 | minHeight = 0,
235 | maxHeight = Constraints.Infinity
236 | )
237 | )
238 | }
239 |
240 | val placeStrategy = measurables.map { it.parentData }
241 |
242 | val minHeight = placeables.minOfOrNull { it.height }
243 | ?.coerceIn(constraints.minHeight, constraints.maxHeight) ?: 0
244 |
245 | val maxHeight = placeables.maxOfOrNull { it.height }
246 | ?.coerceIn(constraints.minHeight, constraints.maxHeight) ?: 0
247 |
248 | val maxWidth = placeables.maxOfOrNull{ it.width }
249 | ?.coerceIn(constraints.minWidth, constraints.maxWidth) ?: 0
250 |
251 | collapsingToolbarState.also {
252 | it.minHeight = minHeight
253 | it.maxHeight = maxHeight
254 | }
255 |
256 | val height = collapsingToolbarState.height
257 | return layout(maxWidth, height) {
258 | val progress = collapsingToolbarState.progress
259 |
260 | placeables.forEachIndexed { i, placeable ->
261 | val strategy = placeStrategy[i]
262 | if(strategy is CollapsingToolbarData) {
263 | strategy.progressListener?.onProgressUpdate(progress)
264 | }
265 |
266 | when(strategy) {
267 | is CollapsingToolbarRoadData -> {
268 | val collapsed = strategy.whenCollapsed
269 | val expanded = strategy.whenExpanded
270 |
271 | val collapsedOffset = collapsed.align(
272 | size = IntSize(placeable.width, placeable.height),
273 | space = IntSize(maxWidth, height),
274 | layoutDirection = layoutDirection
275 | )
276 |
277 | val expandedOffset = expanded.align(
278 | size = IntSize(placeable.width, placeable.height),
279 | space = IntSize(maxWidth, height),
280 | layoutDirection = layoutDirection
281 | )
282 |
283 | val offset = collapsedOffset + (expandedOffset - collapsedOffset) * progress
284 |
285 | placeable.place(offset.x, offset.y)
286 | }
287 | is CollapsingToolbarParallaxData ->
288 | placeable.placeRelative(
289 | x = 0,
290 | y = -((maxHeight - minHeight) * (1 - progress) * strategy.ratio).roundToInt()
291 | )
292 | else -> placeable.placeRelative(0, 0)
293 | }
294 | }
295 | }
296 | }
297 | }
298 |
299 | interface CollapsingToolbarScope {
300 | fun Modifier.progress(listener: ProgressListener): Modifier
301 |
302 | fun Modifier.road(whenCollapsed: Alignment, whenExpanded: Alignment): Modifier
303 |
304 | fun Modifier.parallax(ratio: Float = 0.2f): Modifier
305 |
306 | fun Modifier.pin(): Modifier
307 | }
308 |
309 | internal object CollapsingToolbarScopeInstance: CollapsingToolbarScope {
310 | override fun Modifier.progress(listener: ProgressListener): Modifier {
311 | return this.then(ProgressUpdateListenerModifier(listener))
312 | }
313 |
314 | override fun Modifier.road(whenCollapsed: Alignment, whenExpanded: Alignment): Modifier {
315 | return this.then(RoadModifier(whenCollapsed, whenExpanded))
316 | }
317 |
318 | override fun Modifier.parallax(ratio: Float): Modifier {
319 | return this.then(ParallaxModifier(ratio))
320 | }
321 |
322 | override fun Modifier.pin(): Modifier {
323 | return this.then(PinModifier())
324 | }
325 | }
326 |
327 | internal class RoadModifier(
328 | private val whenCollapsed: Alignment,
329 | private val whenExpanded: Alignment
330 | ): ParentDataModifier {
331 | override fun Density.modifyParentData(parentData: Any?): Any {
332 | return CollapsingToolbarRoadData(
333 | this@RoadModifier.whenCollapsed, this@RoadModifier.whenExpanded,
334 | (parentData as? CollapsingToolbarData)?.progressListener
335 | )
336 | }
337 | }
338 |
339 | internal class ParallaxModifier(
340 | private val ratio: Float
341 | ): ParentDataModifier {
342 | override fun Density.modifyParentData(parentData: Any?): Any {
343 | return CollapsingToolbarParallaxData(ratio, (parentData as? CollapsingToolbarData)?.progressListener)
344 | }
345 | }
346 |
347 | internal class PinModifier: ParentDataModifier {
348 | override fun Density.modifyParentData(parentData: Any?): Any {
349 | return CollapsingToolbarPinData((parentData as? CollapsingToolbarData)?.progressListener)
350 | }
351 | }
352 |
353 | internal class ProgressUpdateListenerModifier(
354 | private val listener: ProgressListener
355 | ): ParentDataModifier {
356 | override fun Density.modifyParentData(parentData: Any?): Any {
357 | return CollapsingToolbarProgressData(listener)
358 | }
359 | }
360 |
361 | fun interface ProgressListener {
362 | fun onProgressUpdate(value: Float)
363 | }
364 |
365 | internal sealed class CollapsingToolbarData(
366 | var progressListener: ProgressListener?
367 | )
368 |
369 | internal class CollapsingToolbarProgressData(
370 | progressListener: ProgressListener?
371 | ): CollapsingToolbarData(progressListener)
372 |
373 | internal class CollapsingToolbarRoadData(
374 | var whenCollapsed: Alignment,
375 | var whenExpanded: Alignment,
376 | progressListener: ProgressListener? = null
377 | ): CollapsingToolbarData(progressListener)
378 |
379 | internal class CollapsingToolbarPinData(
380 | progressListener: ProgressListener? = null
381 | ): CollapsingToolbarData(progressListener)
382 |
383 | internal class CollapsingToolbarParallaxData(
384 | var ratio: Float,
385 | progressListener: ProgressListener? = null
386 | ): CollapsingToolbarData(progressListener)
387 |
--------------------------------------------------------------------------------
/lib/src/main/java/me/onebone/toolbar/CollapsingToolbarScaffold.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2021 onebone
3 | *
4 | * Permission is hereby granted, free of charge, to any person obtaining a copy
5 | * of this software and associated documentation files (the "Software"), to deal
6 | * in the Software without restriction, including without limitation the rights
7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | * copies of the Software, and to permit persons to whom the Software is
9 | * furnished to do so, subject to the following conditions:
10 | *
11 | * The above copyright notice and this permission notice shall be included in all
12 | * copies or substantial portions of the Software.
13 | *
14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 | * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 | * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
20 | * OR OTHER DEALINGS IN THE SOFTWARE.
21 | */
22 |
23 | package me.onebone.toolbar
24 |
25 | import androidx.compose.foundation.gestures.ScrollableDefaults
26 | import androidx.compose.runtime.Composable
27 | import androidx.compose.runtime.Stable
28 | import androidx.compose.runtime.mutableStateOf
29 | import androidx.compose.runtime.remember
30 | import androidx.compose.runtime.saveable.Saver
31 | import androidx.compose.runtime.saveable.SaverScope
32 | import androidx.compose.runtime.saveable.rememberSaveable
33 | import androidx.compose.ui.Alignment
34 | import androidx.compose.ui.Modifier
35 | import androidx.compose.ui.input.nestedscroll.nestedScroll
36 | import androidx.compose.ui.layout.Layout
37 | import androidx.compose.ui.layout.ParentDataModifier
38 | import androidx.compose.ui.platform.LocalLayoutDirection
39 | import androidx.compose.ui.unit.Density
40 | import androidx.compose.ui.unit.IntSize
41 | import kotlin.math.max
42 |
43 | @Stable
44 | class CollapsingToolbarScaffoldState(
45 | val toolbarState: CollapsingToolbarState,
46 | initialOffsetY: Int = 0
47 | ) {
48 | val offsetY: Int
49 | get() = offsetYState.value
50 |
51 | internal val offsetYState = mutableStateOf(initialOffsetY)
52 | }
53 |
54 | private class CollapsingToolbarScaffoldStateSaver: Saver> {
55 | override fun restore(value: List): CollapsingToolbarScaffoldState =
56 | CollapsingToolbarScaffoldState(
57 | CollapsingToolbarState(value[0] as Int),
58 | value[1] as Int
59 | )
60 |
61 | override fun SaverScope.save(value: CollapsingToolbarScaffoldState): List =
62 | listOf(
63 | value.toolbarState.height,
64 | value.offsetY
65 | )
66 | }
67 |
68 | @Composable
69 | fun rememberCollapsingToolbarScaffoldState(
70 | toolbarState: CollapsingToolbarState = rememberCollapsingToolbarState()
71 | ): CollapsingToolbarScaffoldState {
72 | return rememberSaveable(toolbarState, saver = CollapsingToolbarScaffoldStateSaver()) {
73 | CollapsingToolbarScaffoldState(toolbarState)
74 | }
75 | }
76 |
77 | interface CollapsingToolbarScaffoldScope {
78 | @ExperimentalToolbarApi
79 | fun Modifier.align(alignment: Alignment): Modifier
80 | }
81 |
82 | @Composable
83 | fun CollapsingToolbarScaffold(
84 | modifier: Modifier,
85 | state: CollapsingToolbarScaffoldState,
86 | scrollStrategy: ScrollStrategy,
87 | enabled: Boolean = true,
88 | toolbarModifier: Modifier = Modifier,
89 | toolbarClipToBounds: Boolean = true,
90 | toolbar: @Composable CollapsingToolbarScope.() -> Unit,
91 | body: @Composable CollapsingToolbarScaffoldScope.() -> Unit
92 | ) {
93 | val flingBehavior = ScrollableDefaults.flingBehavior()
94 | val layoutDirection = LocalLayoutDirection.current
95 |
96 | val nestedScrollConnection = remember(scrollStrategy, state) {
97 | scrollStrategy.create(state.offsetYState, state.toolbarState, flingBehavior)
98 | }
99 |
100 | val toolbarState = state.toolbarState
101 |
102 | Layout(
103 | content = {
104 | CollapsingToolbar(
105 | modifier = toolbarModifier,
106 | clipToBounds = toolbarClipToBounds,
107 | collapsingToolbarState = toolbarState,
108 | ) {
109 | toolbar()
110 | }
111 |
112 | CollapsingToolbarScaffoldScopeInstance.body()
113 | },
114 | modifier = modifier
115 | .then(
116 | if (enabled) {
117 | Modifier.nestedScroll(nestedScrollConnection)
118 | } else {
119 | Modifier
120 | }
121 | )
122 | ) { measurables, constraints ->
123 | check(measurables.size >= 2) {
124 | "the number of children should be at least 2: toolbar, (at least one) body"
125 | }
126 |
127 | val toolbarConstraints = constraints.copy(
128 | minWidth = 0,
129 | minHeight = 0
130 | )
131 | val bodyConstraints = constraints.copy(
132 | minWidth = 0,
133 | minHeight = 0,
134 | maxHeight = when (scrollStrategy) {
135 | ScrollStrategy.ExitUntilCollapsed ->
136 | (constraints.maxHeight - toolbarState.minHeight).coerceAtLeast(0)
137 |
138 | ScrollStrategy.EnterAlways, ScrollStrategy.EnterAlwaysCollapsed ->
139 | constraints.maxHeight
140 | }
141 | )
142 |
143 | val toolbarPlaceable = measurables[0].measure(toolbarConstraints)
144 |
145 | val bodyMeasurables = measurables.subList(1, measurables.size)
146 | val childrenAlignments = bodyMeasurables.map {
147 | (it.parentData as? ScaffoldParentData)?.alignment
148 | }
149 | val bodyPlaceables = bodyMeasurables.map {
150 | it.measure(bodyConstraints)
151 | }
152 |
153 | val toolbarHeight = toolbarPlaceable.height
154 |
155 | val width = max(
156 | toolbarPlaceable.width,
157 | bodyPlaceables.maxOfOrNull { it.width } ?: 0
158 | ).coerceIn(constraints.minWidth, constraints.maxWidth)
159 | val height = max(
160 | toolbarHeight,
161 | bodyPlaceables.maxOfOrNull { it.height } ?: 0
162 | ).coerceIn(constraints.minHeight, constraints.maxHeight)
163 |
164 | layout(width, height) {
165 | bodyPlaceables.forEachIndexed { index, placeable ->
166 | val alignment = childrenAlignments[index]
167 |
168 | if (alignment == null) {
169 | placeable.placeRelative(0, toolbarHeight + state.offsetY)
170 | } else {
171 | val offset = alignment.align(
172 | size = IntSize(placeable.width, placeable.height),
173 | space = IntSize(width, height),
174 | layoutDirection = layoutDirection
175 | )
176 | placeable.place(offset)
177 | }
178 | }
179 | toolbarPlaceable.placeRelative(0, state.offsetY)
180 | }
181 | }
182 | }
183 |
184 | internal object CollapsingToolbarScaffoldScopeInstance: CollapsingToolbarScaffoldScope {
185 | @ExperimentalToolbarApi
186 | override fun Modifier.align(alignment: Alignment): Modifier =
187 | this.then(ScaffoldChildAlignmentModifier(alignment))
188 | }
189 |
190 | private class ScaffoldChildAlignmentModifier(
191 | private val alignment: Alignment
192 | ) : ParentDataModifier {
193 | override fun Density.modifyParentData(parentData: Any?): Any {
194 | return (parentData as? ScaffoldParentData) ?: ScaffoldParentData(alignment)
195 | }
196 | }
197 |
198 | private data class ScaffoldParentData(
199 | var alignment: Alignment? = null
200 | )
201 |
--------------------------------------------------------------------------------
/lib/src/main/java/me/onebone/toolbar/FabPlacement.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2021 onebone
3 | *
4 | * Permission is hereby granted, free of charge, to any person obtaining a copy
5 | * of this software and associated documentation files (the "Software"), to deal
6 | * in the Software without restriction, including without limitation the rights
7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | * copies of the Software, and to permit persons to whom the Software is
9 | * furnished to do so, subject to the following conditions:
10 | *
11 | * The above copyright notice and this permission notice shall be included in all
12 | * copies or substantial portions of the Software.
13 | *
14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 | * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 | * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
20 | * OR OTHER DEALINGS IN THE SOFTWARE.
21 | */
22 |
23 | package me.onebone.toolbar
24 |
25 | import androidx.compose.runtime.Immutable
26 |
27 | @Immutable
28 | class FabPlacement(
29 | val left: Int,
30 | val width: Int,
31 | val height: Int
32 | )
--------------------------------------------------------------------------------
/lib/src/main/java/me/onebone/toolbar/FabPosition.kt:
--------------------------------------------------------------------------------
1 | package me.onebone.toolbar
2 |
3 | enum class FabPosition {
4 | Center,
5 | End
6 | }
--------------------------------------------------------------------------------
/lib/src/main/java/me/onebone/toolbar/ScrollStrategy.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2021 onebone
3 | *
4 | * Permission is hereby granted, free of charge, to any person obtaining a copy
5 | * of this software and associated documentation files (the "Software"), to deal
6 | * in the Software without restriction, including without limitation the rights
7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | * copies of the Software, and to permit persons to whom the Software is
9 | * furnished to do so, subject to the following conditions:
10 | *
11 | * The above copyright notice and this permission notice shall be included in all
12 | * copies or substantial portions of the Software.
13 | *
14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 | * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 | * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
20 | * OR OTHER DEALINGS IN THE SOFTWARE.
21 | */
22 |
23 | package me.onebone.toolbar
24 |
25 | import androidx.compose.foundation.gestures.FlingBehavior
26 | import androidx.compose.runtime.MutableState
27 | import androidx.compose.ui.geometry.Offset
28 | import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
29 | import androidx.compose.ui.input.nestedscroll.NestedScrollSource
30 | import androidx.compose.ui.unit.Velocity
31 |
32 | enum class ScrollStrategy {
33 | EnterAlways {
34 | override fun create(
35 | offsetY: MutableState,
36 | toolbarState: CollapsingToolbarState,
37 | flingBehavior: FlingBehavior
38 | ): NestedScrollConnection =
39 | EnterAlwaysNestedScrollConnection(offsetY, toolbarState, flingBehavior)
40 | },
41 | EnterAlwaysCollapsed {
42 | override fun create(
43 | offsetY: MutableState,
44 | toolbarState: CollapsingToolbarState,
45 | flingBehavior: FlingBehavior
46 | ): NestedScrollConnection =
47 | EnterAlwaysCollapsedNestedScrollConnection(offsetY, toolbarState, flingBehavior)
48 | },
49 | ExitUntilCollapsed {
50 | override fun create(
51 | offsetY: MutableState,
52 | toolbarState: CollapsingToolbarState,
53 | flingBehavior: FlingBehavior
54 | ): NestedScrollConnection =
55 | ExitUntilCollapsedNestedScrollConnection(toolbarState, flingBehavior)
56 | };
57 |
58 | internal abstract fun create(
59 | offsetY: MutableState,
60 | toolbarState: CollapsingToolbarState,
61 | flingBehavior: FlingBehavior
62 | ): NestedScrollConnection
63 | }
64 |
65 | private class ScrollDelegate(
66 | private val offsetY: MutableState
67 | ) {
68 | private var scrollToBeConsumed: Float = 0f
69 |
70 | fun doScroll(delta: Float) {
71 | val scroll = scrollToBeConsumed + delta
72 | val scrollInt = scroll.toInt()
73 |
74 | scrollToBeConsumed = scroll - scrollInt
75 |
76 | offsetY.value += scrollInt
77 | }
78 | }
79 |
80 | internal class EnterAlwaysNestedScrollConnection(
81 | private val offsetY: MutableState,
82 | private val toolbarState: CollapsingToolbarState,
83 | private val flingBehavior: FlingBehavior
84 | ): NestedScrollConnection {
85 | private val scrollDelegate = ScrollDelegate(offsetY)
86 | //private val tracker = RelativeVelocityTracker(CurrentTimeProviderImpl())
87 |
88 | override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
89 | val dy = available.y
90 |
91 | val toolbar = toolbarState.height.toFloat()
92 | val offset = offsetY.value.toFloat()
93 |
94 | // -toolbarHeight <= offsetY + dy <= 0
95 | val consume = if(dy < 0) {
96 | val toolbarConsumption = toolbarState.dispatchRawDelta(dy)
97 | val remaining = dy - toolbarConsumption
98 | val offsetConsumption = remaining.coerceAtLeast(-toolbar - offset)
99 | scrollDelegate.doScroll(offsetConsumption)
100 |
101 | toolbarConsumption + offsetConsumption
102 | }else{
103 | val offsetConsumption = dy.coerceAtMost(-offset)
104 | scrollDelegate.doScroll(offsetConsumption)
105 |
106 | val toolbarConsumption = toolbarState.dispatchRawDelta(dy - offsetConsumption)
107 |
108 | offsetConsumption + toolbarConsumption
109 | }
110 |
111 | return Offset(0f, consume)
112 | }
113 |
114 | override suspend fun onPreFling(available: Velocity): Velocity {
115 | val left = if(available.y > 0) {
116 | toolbarState.fling(flingBehavior, available.y)
117 | }else{
118 | // If velocity < 0, the main content should have a remaining scroll space
119 | // so the scroll resumes to the onPreScroll(..., Fling) phase. Hence we do
120 | // not need to process it at onPostFling() manually.
121 | available.y
122 | }
123 |
124 | return Velocity(x = 0f, y = available.y - left)
125 | }
126 | }
127 |
128 | internal class EnterAlwaysCollapsedNestedScrollConnection(
129 | private val offsetY: MutableState,
130 | private val toolbarState: CollapsingToolbarState,
131 | private val flingBehavior: FlingBehavior
132 | ): NestedScrollConnection {
133 | private val scrollDelegate = ScrollDelegate(offsetY)
134 | //private val tracker = RelativeVelocityTracker(CurrentTimeProviderImpl())
135 |
136 | override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
137 | val dy = available.y
138 |
139 | val consumed = if(dy > 0) { // expanding: offset -> body -> toolbar
140 | val offsetConsumption = dy.coerceAtMost(-offsetY.value.toFloat())
141 | scrollDelegate.doScroll(offsetConsumption)
142 |
143 | offsetConsumption
144 | }else{ // collapsing: toolbar -> offset -> body
145 | val toolbarConsumption = toolbarState.dispatchRawDelta(dy)
146 | val offsetConsumption = (dy - toolbarConsumption).coerceAtLeast(-toolbarState.height.toFloat() - offsetY.value)
147 |
148 | scrollDelegate.doScroll(offsetConsumption)
149 |
150 | toolbarConsumption + offsetConsumption
151 | }
152 |
153 | return Offset(0f, consumed)
154 | }
155 |
156 | override fun onPostScroll(
157 | consumed: Offset,
158 | available: Offset,
159 | source: NestedScrollSource
160 | ): Offset {
161 | val dy = available.y
162 |
163 | return if(dy > 0) {
164 | Offset(0f, toolbarState.dispatchRawDelta(dy))
165 | }else{
166 | Offset(0f, 0f)
167 | }
168 | }
169 |
170 | override suspend fun onPostFling(consumed: Velocity, available: Velocity): Velocity {
171 | val dy = available.y
172 |
173 | val left = if(dy > 0) {
174 | // onPostFling() has positive available scroll value only called if the main scroll
175 | // has leftover scroll, i.e. the scroll of the main content has done. So we just process
176 | // fling if the available value is positive.
177 | toolbarState.fling(flingBehavior, dy)
178 | }else{
179 | dy
180 | }
181 |
182 | return Velocity(x = 0f, y = available.y - left)
183 | }
184 | }
185 |
186 | internal class ExitUntilCollapsedNestedScrollConnection(
187 | private val toolbarState: CollapsingToolbarState,
188 | private val flingBehavior: FlingBehavior
189 | ): NestedScrollConnection {
190 | override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
191 | val dy = available.y
192 |
193 | val consume = if(dy < 0) { // collapsing: toolbar -> body
194 | toolbarState.dispatchRawDelta(dy)
195 | }else{
196 | 0f
197 | }
198 |
199 | return Offset(0f, consume)
200 | }
201 |
202 | override fun onPostScroll(
203 | consumed: Offset,
204 | available: Offset,
205 | source: NestedScrollSource
206 | ): Offset {
207 | val dy = available.y
208 |
209 | val consume = if(dy > 0) { // expanding: body -> toolbar
210 | toolbarState.dispatchRawDelta(dy)
211 | }else{
212 | 0f
213 | }
214 |
215 | return Offset(0f, consume)
216 | }
217 |
218 | override suspend fun onPreFling(available: Velocity): Velocity {
219 | val left = if(available.y < 0) {
220 | toolbarState.fling(flingBehavior, available.y)
221 | }else{
222 | available.y
223 | }
224 |
225 | return Velocity(x = 0f, y = available.y - left)
226 | }
227 |
228 | override suspend fun onPostFling(consumed: Velocity, available: Velocity): Velocity {
229 | val velocity = available.y
230 |
231 | val left = if(velocity > 0) {
232 | toolbarState.fling(flingBehavior, velocity)
233 | }else{
234 | velocity
235 | }
236 |
237 | return Velocity(x = 0f, y = available.y - left)
238 | }
239 | }
240 |
--------------------------------------------------------------------------------
/lib/src/main/java/me/onebone/toolbar/ToolbarWithFabScaffold.kt:
--------------------------------------------------------------------------------
1 | package me.onebone.toolbar
2 |
3 | import androidx.compose.runtime.Composable
4 | import androidx.compose.ui.Modifier
5 | import androidx.compose.ui.layout.SubcomposeLayout
6 | import androidx.compose.ui.unit.LayoutDirection
7 | import androidx.compose.ui.unit.dp
8 |
9 | @ExperimentalToolbarApi
10 | @Composable
11 | fun ToolbarWithFabScaffold(
12 | modifier: Modifier,
13 | state: CollapsingToolbarScaffoldState,
14 | scrollStrategy: ScrollStrategy,
15 | toolbarModifier: Modifier = Modifier,
16 | toolbarClipToBounds: Boolean = true,
17 | toolbar: @Composable CollapsingToolbarScope.() -> Unit,
18 | fab: @Composable () -> Unit,
19 | fabPosition: FabPosition = FabPosition.End,
20 | body: @Composable CollapsingToolbarScaffoldScope.() -> Unit
21 | ) {
22 | SubcomposeLayout(
23 | modifier = modifier
24 | ) { constraints ->
25 |
26 | val toolbarScaffoldConstraints = constraints.copy(
27 | minWidth = 0,
28 | minHeight = 0,
29 | maxHeight = constraints.maxHeight
30 | )
31 |
32 | val toolbarScaffoldPlaceables = subcompose(ToolbarWithFabScaffoldContent.ToolbarScaffold) {
33 | CollapsingToolbarScaffold(
34 | modifier = modifier,
35 | state = state,
36 | scrollStrategy = scrollStrategy,
37 | toolbarModifier = toolbarModifier,
38 | toolbarClipToBounds = toolbarClipToBounds,
39 | toolbar = toolbar,
40 | body = body
41 | )
42 | }.map { it.measure(toolbarScaffoldConstraints) }
43 |
44 | val fabConstraints = constraints.copy(
45 | minWidth = 0,
46 | minHeight = 0
47 | )
48 |
49 | val fabPlaceables = subcompose(
50 | ToolbarWithFabScaffoldContent.Fab,
51 | fab
52 | ).mapNotNull { measurable ->
53 | measurable.measure(fabConstraints).takeIf { it.height != 0 && it.width != 0 }
54 | }
55 |
56 | val fabPlacement = if (fabPlaceables.isNotEmpty()) {
57 | val fabWidth = fabPlaceables.maxOfOrNull { it.width } ?: 0
58 | val fabHeight = fabPlaceables.maxOfOrNull { it.height } ?: 0
59 | // FAB distance from the left of the layout, taking into account LTR / RTL
60 | val fabLeftOffset = if (fabPosition == FabPosition.End) {
61 | if (layoutDirection == LayoutDirection.Ltr) {
62 | constraints.maxWidth - 16.dp.roundToPx() - fabWidth
63 | } else {
64 | 16.dp.roundToPx()
65 | }
66 | } else {
67 | (constraints.maxWidth - fabWidth) / 2
68 | }
69 |
70 | FabPlacement(
71 | left = fabLeftOffset,
72 | width = fabWidth,
73 | height = fabHeight
74 | )
75 | } else {
76 | null
77 | }
78 |
79 | val fabOffsetFromBottom = fabPlacement?.let {
80 | it.height + 16.dp.roundToPx()
81 | }
82 |
83 | val width = constraints.maxWidth
84 | val height = constraints.maxHeight
85 |
86 | layout(width, height) {
87 | toolbarScaffoldPlaceables.forEach {
88 | it.place(0, 0)
89 | }
90 |
91 | fabPlacement?.let { placement ->
92 | fabPlaceables.forEach {
93 | it.place(placement.left, height - fabOffsetFromBottom!!)
94 | }
95 | }
96 |
97 | }
98 |
99 | }
100 | }
101 |
102 | private enum class ToolbarWithFabScaffoldContent {
103 | ToolbarScaffold, Fab
104 | }
105 |
--------------------------------------------------------------------------------
/lib/src/test/java/me/onebone/toolbar/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package me.onebone.toolbar
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':lib'
2 | include ':app'
3 | rootProject.name = "Collapsing Toolbar"
4 |
--------------------------------------------------------------------------------