Set onClick onLongPress on Button in KMP Compose Multiplatform

Today’s tutorial will teach us how to implement onClick onLongPress on Button in KMP Kotlin Compose Multiplatform for Android and iOS platforms. This guide includes step-by-step processes, explanations of all the properties, and coding examples for handling click and long-click events.

Set onClick onLongPress on Button in KMP Compose Multiplatform

Set onClick onLongPress on Button in KMP Compose Multiplatform

After extensive research in KMM(Kotlin Multiplatform Mobile), I found that the official button widget does not natively support the onLongPress event. It currently only supports the onClick event. So, to work around this and find a solution, I have integrated onClick and onLongPress into the Box widget. The Box widget supports all native events, including the ripple effect. It works like a button because I designed it at the button place.

Code for custom button using Box:

Calling method:

Code explanation:

I have written the code in Custom widget format. You must copy and paste the code, and you can reuse the button multiple times.

  • fillMaxSize(): This function will set the Box button width to fill parent.
  • background: To set the background color of the Box button widget.
  • shape: Pass your desired shape; I am passing a rounded corner shape with a corner radius.
  • indication: Enable ripple effect on Box widget.
  • combinedClickable: Enable both onClick onLongPress on Box widget.
  • contentAlignment: Setting Box inside child Text alignment vertically and horizontally center.

Complete source code for App.kt file:

Screenshot of Android device:

Box Button in KMP

Screenshot in iOS device:

Button Box in iOS KMP

Output:

Set onClick onLongPress on Button in KMP Compose Multiplatform

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *