Skip to content

Commit e1631c0

Browse files
committed
Adds snippet for the "Create a parallax scrolling effect" doc at https://developer.android.com/quick-guides/content/parallax-scrolling?hl=en
1 parent 0346b45 commit e1631c0

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,59 @@
11
package com.example.compose.snippets.images
22

3+
import androidx.compose.foundation.Image
4+
import androidx.compose.foundation.ScrollState
5+
import androidx.compose.foundation.background
6+
import androidx.compose.foundation.layout.Column
7+
import androidx.compose.foundation.layout.fillMaxWidth
8+
import androidx.compose.foundation.layout.padding
9+
import androidx.compose.foundation.rememberScrollState
10+
import androidx.compose.foundation.verticalScroll
11+
import androidx.compose.material3.Text
12+
import androidx.compose.runtime.Composable
13+
import androidx.compose.ui.Modifier
14+
import androidx.compose.ui.graphics.Color
15+
import androidx.compose.ui.layout.ContentScale
16+
import androidx.compose.ui.layout.layout
17+
import androidx.compose.ui.res.painterResource
18+
import androidx.compose.ui.res.stringResource
19+
import androidx.compose.ui.unit.dp
20+
import com.example.compose.snippets.R
21+
22+
// [START android_compose_images_parallax]
23+
@Composable
24+
fun ParallaxEffect()
25+
{
26+
fun Modifier.parallaxLayoutModifier(scrollState: ScrollState, rate: Int) =
27+
layout { measurable, constraints ->
28+
val placeable = measurable.measure(constraints)
29+
val height = if (rate > 0) scrollState.value / rate else scrollState.value
30+
layout(placeable.width, placeable.height) {
31+
placeable.place(0, height)
32+
}
33+
}
34+
35+
val scrollState = rememberScrollState()
36+
Column(
37+
modifier = Modifier
38+
.fillMaxWidth()
39+
.verticalScroll(scrollState),
40+
) {
41+
42+
Image(
43+
painterResource(id = R.drawable.cupcake),
44+
contentDescription = "Android logo",
45+
contentScale = ContentScale.Fit,
46+
// Reduce scrolling rate by half.
47+
modifier = Modifier.parallaxLayoutModifier(scrollState, 2)
48+
)
49+
50+
Text(
51+
text = stringResource(R.string.detail_placeholder),
52+
modifier = Modifier
53+
.background(Color.White)
54+
.padding(horizontal = 8.dp),
55+
56+
)
57+
}
58+
}
59+
// [END android_compose_images_parallax]

compose/snippets/src/main/res/values/strings.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,4 +52,5 @@
5252
<string name="favorites">Favorites</string>
5353
<string name="shopping">Shopping</string>
5454
<string name="profile">Profile</string>
55+
<string name="detail_placeholder">This is just a placeholder.</string>
5556
</resources>

0 commit comments

Comments
 (0)