Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the ItemDecoration for Jetpack Compose LazyColumn?

In JetpackCompose, we can use LazyColumnFor as RecyclerView.

In RecyclerView, to have a proper margin/padding between items, we need to use ItemDecoration, as per this article

Like below

class MarginItemDecoration(private val spaceHeight: Int) : RecyclerView.ItemDecoration() {
    override fun getItemOffsets(outRect: Rect, view: View,
                                parent: RecyclerView, state: RecyclerView.State) {
        with(outRect) {
            if (parent.getChildAdapterPosition(view) == 0) {
                top = spaceHeight
            }
            left =  spaceHeight
            right = spaceHeight
            bottom = spaceHeight
        }
    }
}

For JetpackCompose LazyColumnFor, what's the equivalent of ItemDecoration?

like image 819
Elye Avatar asked Dec 12 '20 03:12

Elye


People also ask

How is a LazyColumn different than a regular column?

As the name suggests, the difference between LazyColumn and LazyRow is the orientation in which they lay out their items and scroll. LazyColumn produces a vertically scrolling list, and LazyRow produces a horizontally scrolling list. The Lazy components are different to most layouts in Compose.

What are the benefits of jetpack compose?

The key benefits of Jetpack Compose are that it speeds up testing and uses a single code base to write code. There is, therefore, less chance of producing errors. Let's look at the User Profile Image app that loaded images, and information about users from a rest API, using an intuitive design.

Is jetpack compose hard to learn?

Creating your first Jetpack Compose project is surprisingly easy. Just download the latest Canary version of Android studio and select a new Compose project from the list of possible Android projects. To start you'll have a simple “Hello world!” Text composable.


Video Answer


1 Answers

You can use Arrangement.spacedBy() to add spacing in-between items.

Something like:

LazyColumn(
    verticalArrangement = Arrangement.spacedBy(8.dp),
) {
    // ...
}

The example below adds 8.dp of space in-between each item

Before and after:
enter image description here enter image description here

If you want to add padding around the edges of the content you can use the contentPadding parameter.

  LazyColumn(
        verticalArrangement = Arrangement.spacedBy(8.dp),
        contentPadding = PaddingValues(horizontal = 24.dp, vertical = 8.dp)
  ){ ...  }

In the example above, the first item will add 8.dp padding to it’s top, the last item will add 8.dp to its bottom, and all items will have 24.dp padding on the left and the right.

enter image description here

like image 64
Gabriele Mariotti Avatar answered Oct 05 '22 07:10

Gabriele Mariotti