Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Pager] Add VerticalPager #254

Merged
merged 8 commits into from
Mar 17, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 40 additions & 7 deletions docs/pager.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,23 @@

A library which provides paging layouts for Jetpack Compose. If you've used Android's [`ViewPager`](https://developer.android.com/reference/kotlin/androidx/viewpager/widget/ViewPager) before, it has similar properties.

<video width="300" controls loop>
<source src="demo.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>

!!! warning
The pager layouts are currently experimental and the APIs could change at any time.
All of the APIs are marked with the `@ExperimentalPagerApi` annotation.

## HorizontalPager

`HorizontalPager` is a layout which lays out items in a horizontal row, and allows the user to swipe between pages.

<figure>
<video width="300" controls loop>
<source src="horiz_demo.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<figcaption>HorizontalPager</figcaption>
</figure>


The simplest usage looks like the following:

``` kotlin
Expand All @@ -28,13 +36,38 @@ HorizontalPager(state = pagerState) { page ->
}
```

## VerticalPager

`VerticalPager` is similar to `HorizontalPager` but items are instead laid out vertically, and react to vertical scrolls from the user:

<figure>
<video width="300" controls loop>
<source src="vert_demo.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<figcaption>VerticalPager</figcaption>
</figure>

``` kotlin
// Display 10 items
val pagerState = rememberPagerState(pageCount = 10)

VerticalPager(state = pagerState) { page ->
// Our page content
Text(
text = "Page: $page",
modifier = Modifier.fillMaxWidth()
)
}
```

## Lazy creation

Pages in a `HorizontalPager` are lazily created and laid-out as required by the layout. As the user scrolls through pages, any pages which are no longer required are removed from the content.
Pages in both `HorizontalPager` & `VerticalPager` are lazily created and laid-out as required by the layout. As the user scrolls through pages, any pages which are no longer required are removed from the content.

### Offscreen Limit

HorizontalPager allows the setting of the `offscreenLimit`, which defines the number of pages that should be retained on either side of the current page. Pages beyond this limit will be removed, and then recreated when needed. This value defaults to `1`, but can be increased to enable pre-loading of more content:
Both `HorizontalPager` & `VerticalPager` allow the setting of the `offscreenLimit`, which defines the number of pages that should be retained on either side of the current page. Pages beyond this limit will be removed, and then recreated when needed. This value defaults to `1`, but can be increased to enable pre-loading of more content:

```kotlin
HorizontalPager(
Expand Down
Binary file removed docs/pager/demo.mp4
Binary file not shown.
Binary file added docs/pager/horiz_demo.mp4
Binary file not shown.
Binary file added docs/pager/vert_demo.mp4
Binary file not shown.
9 changes: 8 additions & 1 deletion pager/api/pager.api
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@ public abstract interface annotation class com/google/accompanist/pager/Experime
}

public final class com/google/accompanist/pager/Pager {
public static final fun HorizontalPager (Lcom/google/accompanist/pager/PagerState;Landroidx/compose/ui/Modifier;ZILandroidx/compose/animation/core/DecayAnimationSpec;Landroidx/compose/animation/core/AnimationSpec;Lkotlin/jvm/functions/Function4;Landroidx/compose/runtime/Composer;II)V
public static final fun HorizontalPager (Lcom/google/accompanist/pager/PagerState;Landroidx/compose/ui/Modifier;ZILandroidx/compose/foundation/gestures/FlingBehavior;Lkotlin/jvm/functions/Function4;Landroidx/compose/runtime/Composer;II)V
public static final fun VerticalPager (Lcom/google/accompanist/pager/PagerState;Landroidx/compose/ui/Modifier;ZILandroidx/compose/foundation/gestures/FlingBehavior;Lkotlin/jvm/functions/Function4;Landroidx/compose/runtime/Composer;II)V
}

public final class com/google/accompanist/pager/PagerDefaults {
public static final field $stable I
public static final field INSTANCE Lcom/google/accompanist/pager/PagerDefaults;
public final fun defaultPagerFlingConfig (Lcom/google/accompanist/pager/PagerState;Landroidx/compose/animation/core/DecayAnimationSpec;Landroidx/compose/animation/core/AnimationSpec;Landroidx/compose/runtime/Composer;II)Landroidx/compose/foundation/gestures/FlingBehavior;
}

public abstract interface class com/google/accompanist/pager/PagerScope : androidx/compose/foundation/layout/BoxScope {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.accompanist.pager

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.text.BasicText
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.SemanticsNodeInteraction
import androidx.compose.ui.test.assertHeightIsAtLeast
import androidx.compose.ui.test.assertLeftPositionInRootIsEqualTo
import androidx.compose.ui.test.assertTopPositionInRootIsEqualTo
import androidx.compose.ui.test.assertWidthIsEqualTo
import androidx.compose.ui.test.getUnclippedBoundsInRoot
import androidx.compose.ui.test.onRoot
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.height
import androidx.compose.ui.unit.width
import androidx.test.filters.LargeTest
import org.junit.runner.RunWith
import org.junit.runners.Parameterized

@OptIn(ExperimentalPagerApi::class) // Pager is currently experimental
@LargeTest
@RunWith(Parameterized::class)
class HorizontalPagerTest(
private val itemWidthFraction: Float,
offscreenLimit: Int,
layoutDirection: LayoutDirection,
) : PagerTest(
offscreenLimit = offscreenLimit,
layoutDirection = layoutDirection,
) {
companion object {
@JvmStatic
@Parameterized.Parameters
fun data(): Collection<Array<Any>> = listOf(
// itemWidthFraction, offscreenLimit, layoutDirection

// Test typical full-width items
arrayOf(1f, 2, LayoutDirection.Ltr),
arrayOf(1f, 2, LayoutDirection.Rtl),

// Test an increased offscreenLimit
arrayOf(1f, 4, LayoutDirection.Ltr),
arrayOf(1f, 4, LayoutDirection.Rtl),

// Test items with 80% widths
arrayOf(0.8f, 2, LayoutDirection.Ltr),
arrayOf(0.8f, 2, LayoutDirection.Rtl),
)
}

override fun SemanticsNodeInteraction.swipeAcrossCenter(
velocity: Float,
distancePercentage: Float
): SemanticsNodeInteraction = swipeAcrossCenterWithVelocity(
distancePercentageX = when (layoutDirection) {
LayoutDirection.Rtl -> -distancePercentage
else -> distancePercentage
},
velocity = velocity,
)

override fun SemanticsNodeInteraction.assertLaidOutItemPosition(
page: Int,
currentPage: Int,
): SemanticsNodeInteraction {
val rootBounds = composeTestRule.onRoot().getUnclippedBoundsInRoot()
val expectedItemSize = rootBounds.width * itemWidthFraction

// The expected coordinates. This uses the implicit fact that Pager
// centers items horizontally, and that we're using items with an aspect ratio of 1:1
val expectedTop = (rootBounds.height - expectedItemSize) / 2
val expectedFirstItemLeft = (rootBounds.width - expectedItemSize) / 2

return assertWidthIsEqualTo(expectedItemSize)
.assertHeightIsAtLeast(expectedItemSize)
.assertTopPositionInRootIsEqualTo(expectedTop)
.run {
if (layoutDirection == LayoutDirection.Ltr) {
assertLeftPositionInRootIsEqualTo(
expectedFirstItemLeft + (expectedItemSize * (page - currentPage))
)
} else { // layoutDirection = RTL
assertLeftPositionInRootIsEqualTo(
expectedFirstItemLeft - (expectedItemSize * (page - currentPage))
)
}
}
}

override fun setPagerContent(
layoutDirection: LayoutDirection,
pageCount: Int,
offscreenLimit: Int,
): PagerState {
val pagerState = PagerState(pageCount = pageCount)
composeTestRule.setContent(layoutDirection) {
HorizontalPager(
state = pagerState,
offscreenLimit = offscreenLimit,
modifier = Modifier.fillMaxSize()
) { page ->
Box(
modifier = Modifier
.fillMaxWidth(itemWidthFraction)
.aspectRatio(1f)
.background(randomColor())
.testTag(page.toString())
) {
BasicText(
text = page.toString(),
modifier = Modifier.align(Alignment.Center)
)
}
}
}
return pagerState
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import org.junit.runners.JUnit4

@OptIn(ExperimentalPagerApi::class) // Pager is currently experimental
@RunWith(JUnit4::class)
class PagerUnitTest {
class PagerStateUnitTest {
@get:Rule
val composeTestRule = createComposeRule()

Expand Down
Loading