Search code examples
androidkotlinandroid-jetpack-composelazycolumnandroid-jetpack-compose-material3

How to remove Surface padding in jetpack compose


In LazyColumn when we use LazyListScope.items with Surface. Inside multiple items there is extra padding on TOP and BOTTOM. I want to remove this padding. I am using Surface component of Material 3. BOM version is compose_bom = "2022.11.00".

Please don't suggest any alpha or beta version fix. If Material 3 stable api don't have solution, then please suggest normal Surface Material.

PreviewCreateListView

@Preview(showBackground = true)
@Composable
fun PreviewCreateListView() {
    CreateListView()
}

CreateListView

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CreateListView() {
    val itemList = listOf(1, 2, 3)
    LazyColumn(
        contentPadding = PaddingValues(16.dp),
    ) {
        items(itemList) { item ->
            Surface(
                onClick = { },
                color = Color.Blue
            ) {
                Text(
                    modifier = Modifier.fillMaxWidth(),
                    text = "$item",
                )
            }
        }
    }
}

Output

enter image description here


Solution

  • The M3 Surface with the onClick parameter has a minimum touch target size (48.dp) for accessibility. It will include extra space outside the component to ensure that they are accessible.

    You can override this behavior by applying false to the LocalMinimumInteractiveComponentEnforcement. If it is set to false there will be no extra space.

    You can override this behavior by setting Dp.Unspecified or your specific min size to the LocalMinimumInteractiveComponentSize.

    Something like:

    CompositionLocalProvider(
        // Deprecated starting on Version 1.3.0-alpha04
        // https://developer.android.com/jetpack/androidx/releases/compose-material3#1.3.0-alpha04
        // LocalMinimumInteractiveComponentEnforcement provides false
        LocalMinimumInteractiveComponentSize provides Dp.Unspecified
    ) {
        
        Surface(
            onClick = { },
            color = Color.Blue
        ) {
            Text(
                modifier = Modifier.fillMaxWidth(),
                text = "$item",
            )
        }
    }
    

    enter image description here

    Note: LocalMinimumInteractiveComponentEnforcement requires at least M2 1.4.0-alpha04 and M3 1.1.0-alpha04. Before you can use LocalMinimumTouchTargetEnforcement in the same way.