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-indicator] Support indicator of looping page with infinite page size #1158

Merged
merged 8 commits into from
May 18, 2022
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
4 changes: 2 additions & 2 deletions pager-indicators/api/current.api
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
package com.google.accompanist.pager {

public final class PagerIndicatorKt {
method @androidx.compose.runtime.Composable @com.google.accompanist.pager.ExperimentalPagerApi public static void HorizontalPagerIndicator(com.google.accompanist.pager.PagerState pagerState, optional androidx.compose.ui.Modifier modifier, optional long activeColor, optional long inactiveColor, optional float indicatorWidth, optional float indicatorHeight, optional float spacing, optional androidx.compose.ui.graphics.Shape indicatorShape);
method @androidx.compose.runtime.Composable @com.google.accompanist.pager.ExperimentalPagerApi public static void VerticalPagerIndicator(com.google.accompanist.pager.PagerState pagerState, optional androidx.compose.ui.Modifier modifier, optional long activeColor, optional long inactiveColor, optional float indicatorHeight, optional float indicatorWidth, optional float spacing, optional androidx.compose.ui.graphics.Shape indicatorShape);
method @androidx.compose.runtime.Composable @com.google.accompanist.pager.ExperimentalPagerApi public static void HorizontalPagerIndicator(com.google.accompanist.pager.PagerState pagerState, optional androidx.compose.ui.Modifier modifier, optional int pageCount, optional kotlin.jvm.functions.Function1<? super java.lang.Integer,java.lang.Integer> pageIndexMapping, optional long activeColor, optional long inactiveColor, optional float indicatorWidth, optional float indicatorHeight, optional float spacing, optional androidx.compose.ui.graphics.Shape indicatorShape);
method @androidx.compose.runtime.Composable @com.google.accompanist.pager.ExperimentalPagerApi public static void VerticalPagerIndicator(com.google.accompanist.pager.PagerState pagerState, optional androidx.compose.ui.Modifier modifier, optional int pageCount, optional kotlin.jvm.functions.Function1<? super java.lang.Integer,java.lang.Integer> pageIndexMapping, optional long activeColor, optional long inactiveColor, optional float indicatorHeight, optional float indicatorWidth, optional float spacing, optional androidx.compose.ui.graphics.Shape indicatorShape);
}

public final class PagerTabKt {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import kotlin.math.absoluteValue
import kotlin.math.sign

/**
* An horizontally laid out indicator for a [HorizontalPager] or [VerticalPager], representing
Expand All @@ -48,6 +50,11 @@ import androidx.compose.ui.unit.dp
*
* @param pagerState the state object of your [Pager] to be used to observe the list's state.
* @param modifier the modifier to apply to this layout.
* @param pageCount the size of indicators should be displayed, defaults to [PagerState.pageCount].
* If you are implementing a looping pager with a much larger [PagerState.pageCount]
* than indicators should displayed, e.g. [Int.MAX_VALUE], specify you real size in this param.
* @param pageIndexMapping describe how to get the position of active indicator by the giving page
* from [PagerState.currentPage], if [pageCount] is not equals to [PagerState.pageCount].
* @param activeColor the color of the active Page indicator
* @param inactiveColor the color of page indicators that are inactive. This defaults to
* [activeColor] with the alpha component set to the [ContentAlpha.disabled].
Expand All @@ -61,6 +68,8 @@ import androidx.compose.ui.unit.dp
fun HorizontalPagerIndicator(
pagerState: PagerState,
modifier: Modifier = Modifier,
pageCount: Int = pagerState.pageCount,
pageIndexMapping: (Int) -> Int = { it },
activeColor: Color = LocalContentColor.current.copy(alpha = LocalContentAlpha.current),
inactiveColor: Color = activeColor.copy(ContentAlpha.disabled),
indicatorWidth: Dp = 8.dp,
Expand All @@ -84,16 +93,20 @@ fun HorizontalPagerIndicator(
.size(width = indicatorWidth, height = indicatorHeight)
.background(color = inactiveColor, shape = indicatorShape)

repeat(pagerState.pageCount) {
repeat(pageCount) {
Box(indicatorModifier)
}
}

Box(
Modifier
.offset {
val scrollPosition = (pagerState.currentPage + pagerState.currentPageOffset)
.coerceIn(0f, (pagerState.pageCount - 1).coerceAtLeast(0).toFloat())
val position = pageIndexMapping(pagerState.currentPage)
val offset = pagerState.currentPageOffset
val next = pageIndexMapping(pagerState.currentPage + offset.sign.toInt())
val scrollPosition = ((next - position) * offset.absoluteValue + position)
.coerceIn(0f, (pageCount - 1).coerceAtLeast(0).toFloat())

IntOffset(
x = ((spacingPx + indicatorWidthPx) * scrollPosition).toInt(),
y = 0
Expand All @@ -119,6 +132,11 @@ fun HorizontalPagerIndicator(
*
* @param pagerState the state object of your [Pager] to be used to observe the list's state.
* @param modifier the modifier to apply to this layout.
* @param pageCount the size of indicators should be displayed, defaults to [PagerState.pageCount].
* If you are implementing a looping pager with a much larger [PagerState.pageCount]
* than indicators should displayed, e.g. [Int.MAX_VALUE], specify you real size in this param.
* @param pageIndexMapping describe how to get the position of active indicator by the giving page
* from [PagerState.currentPage], if [pageCount] is not equals to [PagerState.pageCount].
* @param activeColor the color of the active Page indicator
* @param inactiveColor the color of page indicators that are inactive. This defaults to
* [activeColor] with the alpha component set to the [ContentAlpha.disabled].
Expand All @@ -132,6 +150,8 @@ fun HorizontalPagerIndicator(
fun VerticalPagerIndicator(
pagerState: PagerState,
modifier: Modifier = Modifier,
pageCount: Int = pagerState.pageCount,
pageIndexMapping: (Int) -> Int = { it },
activeColor: Color = LocalContentColor.current.copy(alpha = LocalContentAlpha.current),
inactiveColor: Color = activeColor.copy(ContentAlpha.disabled),
indicatorHeight: Dp = 8.dp,
Expand All @@ -155,16 +175,20 @@ fun VerticalPagerIndicator(
.size(width = indicatorWidth, height = indicatorHeight)
.background(color = inactiveColor, shape = indicatorShape)

repeat(pagerState.pageCount) {
repeat(pageCount) {
Box(indicatorModifier)
}
}

Box(
Modifier
.offset {
val scrollPosition = (pagerState.currentPage + pagerState.currentPageOffset)
.coerceIn(0f, (pagerState.pageCount - 1).coerceAtLeast(0).toFloat())
val position = pageIndexMapping(pagerState.currentPage)
val offset = pagerState.currentPageOffset
val next = pageIndexMapping(pagerState.currentPage + offset.sign.toInt())
val scrollPosition = ((next - position) * offset.absoluteValue + position)
.coerceIn(0f, (pageCount - 1).coerceAtLeast(0).toFloat())

IntOffset(
x = 0,
y = ((spacingPx + indicatorHeightPx) * scrollPosition).toInt(),
Expand Down
9 changes: 9 additions & 0 deletions sample/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,15 @@
<category android:name="com.google.accompanist.sample.SAMPLE_CODE" />
</intent-filter>
</activity>
<activity
android:name=".pager.HorizontalPagerLoopingIndicatorSample"
android:label="@string/horiz_pager_title_looping_indicator"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="com.google.accompanist.sample.SAMPLE_CODE" />
</intent-filter>
</activity>

<activity
android:name=".pager.HorizontalPagerTransitionSample"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
/*
* 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.sample.pager

import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.interaction.DragInteraction
import androidx.compose.foundation.interaction.PressInteraction
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Scaffold
import androidx.compose.material.Surface
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PauseCircle
import androidx.compose.material.icons.filled.PlayCircle
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.pager.HorizontalPager
import com.google.accompanist.pager.HorizontalPagerIndicator
import com.google.accompanist.pager.rememberPagerState
import com.google.accompanist.sample.AccompanistSampleTheme
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.delay

class HorizontalPagerLoopingIndicatorSample : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

setContent {
AccompanistSampleTheme {
Surface {
Sample()
}
}
}
}
}

@OptIn(ExperimentalPagerApi::class)
@Composable
private fun Sample() {
Scaffold(
modifier = Modifier.fillMaxSize()
) { padding ->
Column(
Modifier
.fillMaxSize()
.padding(padding)
) {
// Display 10 items
val pageCount = 10

// We start the pager in the middle of the raw number of pages
val loopingCount = Int.MAX_VALUE
val startIndex = loopingCount / 2
val pagerState = rememberPagerState(initialPage = startIndex)

fun pageMapper(index: Int): Int {
return (index - startIndex).floorMod(pageCount)
}

HorizontalPager(
// Set the raw page count to a really large number
count = loopingCount,
state = pagerState,
// Add 32.dp horizontal padding to 'center' the pages
contentPadding = PaddingValues(horizontal = 32.dp),
// Add some horizontal spacing between items
itemSpacing = 4.dp,
modifier = Modifier
.weight(1f)
.fillMaxWidth()
) { index ->
// We calculate the page from the given index
val page = pageMapper(index)
PagerSampleItem(
page = page,
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1f)
)
}
HorizontalPagerIndicator(
pagerState = pagerState,
modifier = Modifier
.align(Alignment.CenterHorizontally)
.padding(16.dp),
pageCount = pageCount,
pageIndexMapping = ::pageMapper
)

val loopState = remember {
mutableStateOf(true)
}

LoopControl(loopState, Modifier.align(Alignment.CenterHorizontally))

ActionsRow(
pagerState = pagerState,
modifier = Modifier.align(Alignment.CenterHorizontally),
infiniteLoop = true
)

var underDragging by remember {
mutableStateOf(false)
}

LaunchedEffect(key1 = Unit) {
pagerState.interactionSource.interactions.collect { interaction ->
when (interaction) {
is PressInteraction.Press -> underDragging = true
is PressInteraction.Release -> underDragging = false
is PressInteraction.Cancel -> underDragging = false
is DragInteraction.Start -> underDragging = true
is DragInteraction.Stop -> underDragging = false
is DragInteraction.Cancel -> underDragging = false
}
}
}

val looping = loopState.value
if (underDragging.not() && looping) {
LaunchedEffect(key1 = underDragging) {
try {
while (true) {
delay(1000L)
val current = pagerState.currentPage
val currentPos = pageMapper(current)
val nextPage = current + 1
if (underDragging.not()) {
val toPage = nextPage.takeIf { nextPage < pagerState.pageCount } ?: (currentPos + startIndex + 1)
if (toPage > current) {
pagerState.animateScrollToPage(toPage)
} else {
pagerState.scrollToPage(toPage)
}
}
}
} catch (e: CancellationException) {
Log.i("page", "Launched paging cancelled")
}
}
}
}
}
}

@Composable
fun LoopControl(
loopState: MutableState<Boolean>,
modifier: Modifier = Modifier,
) {
IconButton(
onClick = { loopState.value = loopState.value.not() },
modifier = modifier
) {
val icon = if (loopState.value) {
Icons.Default.PauseCircle
} else {
Icons.Default.PlayCircle
}
Icon(imageVector = icon, contentDescription = null)
}
}

private fun Int.floorMod(other: Int): Int = when (other) {
0 -> this
else -> this - floorDiv(other) * other
}
1 change: 1 addition & 0 deletions sample/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
<string name="horiz_pager_with_indicator_title">Horizontal Pager: Indicator</string>
<string name="horiz_pager_with_transition_title">Horizontal Pager: Transition</string>
<string name="horiz_pager_title_looping">Horizontal Pager: Looping</string>
<string name="horiz_pager_title_looping_indicator">Horizontal Pager: Looping with Indicators</string>
<string name="horiz_pager_title_tabs">Horizontal Pager: Tabs</string>
<string name="horiz_pager_title_scroll_content">Horizontal Pager: Scrolling content</string>
<string name="horiz_pager_title_different_paddings">Horizontal Pager: Different paddings</string>
Expand Down