I FIXED the Compose Slider
My first open-source Android library
When Google gives you faulty composables, compose one of your own — Nishant, 2022.
While developing a BMI calculator application to practice with Jetpack Compose, I noticed that the Slider
by Compose is not working as expected. I attempted to create my own composable and fixed the problem.
I hope you can see the issue with the Slider. When I am trying to slide the knob to the left, it isn’t synchronized with the position of my thumb.
I searched the internet hard enough, but I could not find a proper solution to my problem. Hence I decided to create an Android library that would fix this issue.
How did I do it?
My logic is fairly simple when it comes to drawing the design. The main brainpower comes when you need to add touch interactions with the view. I started with the Canvas
composable and drew two overlapping lines and two overlapping circles.
For achieving the input of the user’s touch, I added the pointerInteropFilter
to the modifier
passed down from the function. Based on when the user pressed the finger on the knob (ACTION_DOWN), when the user dragged the knob (ACTION_MOVE), and when the user lifted the finger (ACTION_UP), I performed certain calculations and emitted the new state of value
back to the parent.
You can view the entire code on this link.
Installation
Add the JitPack URL to your settings.gradle
file:
repositories {
maven { url 'https://jitpack.io' }
}
And add the following dependency to your build.gradle
file:
dependencies {
implementation "com.github.cybercoder-naj:sliding-bar:$version"
}
Usage/Examples
Remember to add the @ExperimentalComposeUiApi
annotation to your class/function.
SlidingBar(
value = value,
onValueChanged = { value = it },
modifier = Modifier
.padding(horizontal = 64.dp)
.fillMaxWidth(),
colors = SlidingBarDefaults.colors(
colorPrimary = Color.Green,
colorTrack = Color.Blue
),
valueRange = 0f..30f,
stepSize = 1f
)
The demo is available here.
Conclusion
I did not see a valid solution to my code; hence, with a little math, I created a version that seems to work perfectly based on my requirements.
You are welcome to contribute to my open-source project on GitHub. Any contribution will be appreciated. No contribution is considered big or small.