PetrHoracek
PetrHoracek

Reputation: 113

Custom shape size in Jetpack Compose

Is there a way to add your own shape size in Jetpack Compose using Kotlin extensions?

Default Shapes class implementation in Jetpack Compose:

val Shapes = Shapes(
   small = RoundedCornerShape(4.dp),
   medium = RoundedCornerShape(4.dp),
   large = RoundedCornerShape(0.dp)
)

This is how I tried to add a new shape size:

val Shapes.ExtraLarge: CornerBasedShape
get() = RoundedCornerShape(16.dp)

But I am getting the Receiver parameter is never used warning and cannot use the new size in my Composables. Thanks for any advice!

Upvotes: 2

Views: 1272

Answers (2)

Sebastian Rieger
Sebastian Rieger

Reputation: 705

We have done this with our colors multiple times, but it's possible to extend the Shapes, Colors or Typography all the same way.

val Shapes = Shapes(
        small = RoundedCornerShape(4.dp),
        medium = RoundedCornerShape(10.dp),
        large = RoundedCornerShape(12.dp)
).apply {
    test = RoundedCornerShape(16.dp)
}

var Shapes.test: CornerBasedShape

It's very easy and possible without any annotation.

The first step is to create an extension field for the class. After that you can use the apply method to extend the constructor call with your own value.

The new shape can be called simply like any other shape like this

MaterialTheme.shapes.test

Upvotes: 1

Rafsanjani
Rafsanjani

Reputation: 5443

You need to add @get for top level composable extension functions.

@get:Composable
val Shapes.ExtraLarge : CornerBasedShape
    get() = RoundedCornerShape(16.dp)

But if you see yourself doing this several times, then it's an indication that you need to start defining a custom design system where you can define properties such as colors and shapes that have logical meaning to your business/organization.

https://developer.android.com/jetpack/compose/themes/custom

Upvotes: 1

Related Questions