3

I want to show a custom Indication when a button is clicked. The indication should be rounded in the corners and overlay a darker color. So far I was able to achieve this with the following code

Modifier.clickable(onClick = {}, indication = PressedIndication)
object PressedIndication : Indication {

    private object DefaultIndicationInstance : IndicationInstance {
        override fun ContentDrawScope.drawIndication(interactionState: InteractionState) {
            drawContent()
            if (interactionState.contains(Interaction.Pressed)) drawRoundRect(
                cornerRadius = CornerRadius(4f, 4f), //<-- How to use dp values?
                color = Color.Black.copy(
                    alpha = 0.3f
                ), size = size
            )

        }
    }

    override fun createInstance(): IndicationInstance {
        return DefaultIndicationInstance
    }
}

I can achieve rounded corners using drawRoundRect and cornerRadius but is there any way to use dp values?

Note: I cannot use clickable and clip because the clickable area doesn't exactly match the indication area

Yannick
  • 4,833
  • 8
  • 38
  • 63
  • 1
    sounds like you're trying to do the same thing as the owl sample app's introduction screen from the [compose-samples](https://github.com/android/compose-samples) repository. Maybe checking out the source code could help you. – Noah Jan 15 '21 at 08:53

2 Answers2

3

You can pass Dp but you have to adjust to the screen's density. The extension function Dp.toPx() inside a density scoped code block works fine.

val sizeInPx = with(LocalDensity.current) { 16.dp.toPx() }
Louis CAD
  • 10,965
  • 2
  • 39
  • 58
2jan222
  • 1,732
  • 2
  • 16
  • 29
  • I have discovered you can also use `dp.toPx()` directly – Yannick Jan 16 '21 at 23:28
  • 17
    Why the votes?? The question was about converting pixels to dp and not the other way around. – Johann Nov 25 '21 at 15:07
  • The function targeted only accepted px at the time I answered; thus this was the right answer. See here: https://stackoverflow.com/a/42108115/9957384 for density you can use ``LocalDensity.current`` – 2jan222 Nov 25 '21 at 15:30
2

As described by 2jan222 you can convert using Dp.toPx().

In your case you could avoid to build a custom Indication.
You could use something like:

 val interactionSource = remember { MutableInteractionSource() }
 Modifier.clickable(
        interactionSource = interactionSource,
        indication = rememberRipple(
             radius = 4.dp,
             color=Color.Black.copy(alpha = 0.3f))
        ) 
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841