What is a ViewPager

What is a ViewPager? The ViewPager function is to slide the view, just like the desktop slides left and right. ViewPager can be used to switch between pages. ViewPager can be used to switch between pages. It can be used to switch between pages.

A simple example of ViewPager as a carousel graph is shown in the figure above.

By the way, the ViewPager of Android can only be swiped left and right, but in 2019, Google released ViewPager2, which can be swiped left and right as well as vertical, so that the playability has been improved a lot. There is no need to customize viewgroups for the specific needs of the product.

Compose the “ViewPager”

Compose doesn’t have a ViewPager in it. Instead, Google has written a library called Pager into Compose’s extension library, which implements similar functionality to ViewPager in Android.

Add the dependent

As mentioned above, Compose does not have a ViewPager, so you need to add a dependency to build.gradle:

repositories {
    mavenCentral()
}
​
dependencies {
    implementation "com.google.accompanist:accompanist-pager:<version>"
}
Copy the code

Replace the above version with the latest version number, which at the time of writing was 0.24.2-alpha.

Horizontal sliding (left and right)

Add good dependencies to see how they work!

HorizontalPager(count = 10) { page ->
    Text(text = "Page: $page")
}
Copy the code

Yes, it’s that simple. Remember how hard it was to use ViewPager in an Android View… In Compose, only one line of code is required.

The ViewPager preview can be viewed in Android View only if you want to run the ViewPager preview on a real machine or virtual machine, but in Compose you can preview the ViewPager directly. Here’s the preview code:

@OptIn(ExperimentalPagerApi::class)
@Preview(name = "Test1", heightDp = 170)
@Composable
fun PagerTest1Preview() {
    PagerTest1()
}
Copy the code

For a brief introduction to the Preview code above, see OptIn on the first line. This is because the Pager library is currently experimental and the API is subject to change at any time, so all apis are marked with @experimentalPagerAPI annotation, and Preview on the second line. Set the name and height of the preview. Take a look at the results:

This is a preview interaction directly in AS, so it might look a bit sluggish, but on the real phone it’s fine, as smooth as Dove.

Vertical slide (up and down)

It says horizontal sliding, so let’s look at vertical sliding:

VerticalPager(count = 10) { page ->
    Text(text = "Page: $page")
}
Copy the code

A horizontal slide is a HorizontalPager, and a vertical slide is a VerticalPager.

@OptIn(ExperimentalPagerApi::class)
@Preview(name = "Test3", heightDp = 170, widthDp = 100)
@Composable
fun PagerTest3Preview() {
    PagerTest3()
}
Copy the code

The preview code is the same as before, so I won’t have to explain too much, but let’s go straight to the image:

Not bad, very simple code to achieve a more complex effect in the Android View.

The source code parsing

Let’s take a quick look at the Pager source code.

Horizontal slide source code

Let’s take a look at the horizontal sliding source code:

In case you want to look at it, I’ve put the code in a picture, so let’s take a look at the function of the HorizontalPager parameter, or the function of the HorizontalPager.

  • Count: This is the argument that the composable item HorizontalPager must write, which is, as the name suggests, the number of pages
  • Modifier: This Modifier is too much in Compose, so I won’t repeat it
  • State: State object used to control or observe Pager state
  • ReverseLayout: Reverses the direction of scrolling and layout. Default is false, true will be the first item last
  • ItemSpacing: Adds vertical spacing between items
  • ContentPadding: The Padding of the content
  • VerticalAlignment: verticalAlignment is in the center
  • FlingBehavior: Logic describing sliding behavior
  • Key: The scrolling position will be held according to the key
  • UserScrollEnabled: Whether scrolling is allowed by user gestures or accessibility. Even if it is disabled, you can still use this state to programmatically scroll
  • Content: The content of a concrete composable item. In this case, you can refer to PagerScope.CurrentPage and other properties in PagerScope.

Vertical slide source code

Next, look at the source code of vertical sliding:

Did you find anything, horizontal and vertical slide source code is not very similar, and are directly called Pager composable items. There are a lot of parameters that are the same as for horizontal sliding, so I won’t go over them, but let’s look at the different parameters.

  • HorizontalAlignment: the horizontal sliding alignment above is centered vertically, and the horizontalAlignment here is centered horizontally
  • FlingBehavior: The logic that describes the sliding behavior is also different

The rest is pretty much the same.

Pager internal implementation

Let’s take a look at the internal implementation of Pager, again as it’s source code, and put it in an image:

You can see that there is an isVertical parameter in the Pager composable, which is used to determine whether a slide isVertical or horizontal. If a slide isVertical, LazyColumn is used, and if a slide is horizontal, LazyRow is used. Remember? In Compose, the object of LazyColumn and LazyRow is RecyclerView in Android View, Now ViewPager2 in Android View also uses RecyclerView.

Advanced usage

The basic usage of Pager is outlined above, but it’s not as simple as it would be in a production environment. Here are some examples that might be used in a production environment.

Add indicator

What is an indicator? It’s simply the small circle at the bottom of the middle of the GIF at the beginning of the article that tells the user what page they are on and how many pages there are.

Previously, adding indicators to Compose required you to draw them yourself, but now you’ve created a library for implementing Pager indicators.

Add the dependent

The first step is to add a dependency to build.gradle:

repositories { mavenCentral() } dependencies { implementation "com.google.accompanist:accompanist-pager:<version>" // Indicator implementation "com. Google. Accompanist: accompanist - pager - indicators: < version >"}Copy the code

As above, you need to replace version with the current, most recent version, which at the time of writing was 0.24.2-alpha.

Service indicator

Here’s how to use the indicator:

// HorizontalPagerIndicator(pagerState = pagerState, modifier = Modifier .align(Alignment.CenterHorizontally) .padding(16.dp), VerticalPagerIndicator(pagerState = pagerState, modifier = Modifier .align(Alignment.CenterHorizontally) .padding(16.dp), )Copy the code

Not so easy, the indicator is also a composable item that just needs the state you passed in to Pager. The total number of pages and the current page number are both in PagerState. Let’s take a look at the effect picture first:

It can be found from the above code that indicators are also divided into horizontal and vertical indicators. Since horizontal indicators are often used, this paper takes horizontal indicators as the object of explanation.

Above is the source of the level indicator, in fact, and I drew before the principle is the same, but when the official launch of the library must choose to use the official 😂. Method to draw the code, we should be able to understand, the following is the meaning of the parameters:

  • PagerState: Indicates the status of Pager
  • Modifier: modifier without much explanation
  • ActiveColor: Currently active indicator color
  • InactiveColor: Currently inactive indicator color
  • IndicatorWidth: The width of an indicator
  • IndicatorHeight: indicatorHeight
  • Spacing: The width between indicators
  • IndicatorShape: Indicates the shape of an indicator. By default, it is round. You can also define it yourself

The indicator can also be used in combination with TabRow. The effect is basically the same as the page switching effect of wechat. If you are interested, you can try it yourself.

Listen for page changes

In Android View if we want to monitor ViewPager you just need to through registerOnPageChangeCallback method for listening, so we should how to monitor Pager in the Compose page changes?

The PagerState.CurrentPage property is updated every time the selected page changes. You can use the snapshotFlow function to observe the flow changes:

val pagerState = rememberPagerState()
LaunchedEffect(pagerState) {
    snapshotFlow { pagerState.currentPage }.collect { page ->
        AnalyticsService.sendPageSelectedEvent(page)
    }
}
VerticalPager(
    count = 10,
    state = pagerState,
) { page ->
    Text(text = "Page: $page")
}
Copy the code

Modify the Pager switchover effect

As you all know, in Android View, the ViewPager toggle effect can be changed by setting PageTransformer. Take a look at the official Demo sample:

Looking at the effect is good, because it involves too much knowledge, want to learn can go to the official source to view, github.com/google/acco…

Temporary summary

If you want to learn about Compose in a systematic way, you can check out my new book, Jetpack Compose: New UI Programming for Android, which contains the entire Compose framework.

Purchase address of JINGdong

Dangdang Purchase address

Today’s code sample Github:https://github.com/zhujiang521/PlayWeather playing the weather

If it helps you, don’t forget to hit the Star. Thank you very much.

In fact, there are some details that I haven’t covered, so if you have any questions, please feel free to ask in the comments section.

Well, I’ll stop here first, goodbye!