45

Lift on scroll in Jetpack Compose

 2 years ago
source link: https://proandroiddev.com/lift-on-scroll-in-jetpack-compose-ccd05170ea83
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Lift on scroll in Jetpack Compose

Photo by Sven Mieke on Unsplash

Material Design has always specified that top app bars can be positioned at the same elevation as content until that content scrolls, with Material Components for Android providing the app:liftOnScroll attribute.

1*jge_RXeUyDJsX7CJVuAY4Q.gif?q=20
lift-on-scroll-in-jetpack-compose-ccd05170ea83
Source: Material Design — App bars: top

Of course, Jetpack Compose does not have built-in liftOnScroll functionality, so how do we implement this?

Implementing liftOnScroll in Jetpack Compose

Typically you create scrolling content inside a LazyColumn or LazyRow. Both of these provide a state field of type LazyListState, which, as the documentation states, can be hoisted to observe scrolling.

1*-jJ7mByCC0sQAO6c9-ZWxg.png?q=20
lift-on-scroll-in-jetpack-compose-ccd05170ea83
1*DYcpjmUBgykHsr-7-DnLXw.png?q=20
lift-on-scroll-in-jetpack-compose-ccd05170ea83
LazyListState — Public properties

So, by providing a LazyListState when creating our list, we now have access to the first visible items index and scroll offset anywhere in our code.

With that information, it is trivial enough to generate an elevation value to use in an AppBar.

The great thing is this value can be passed around and used in any element, not just AppBars, so if you’ve got a custom toolbar implementation you can still use this trick.

Compare that to liftOnScroll in XML layouts that require the scrollable view to be nested in the right way.

Here, we use it in our AppBar to generate the required elevation behaviour.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK