In my project I wanted to have progress bar that shows how much time you have until your food is not good to eat any longer. I’m not UX specialist, but I know that usually when you see green color you think it’s all ok and red is some danger. So I decided to have small progress bar in each product list item showing time till it should land in trashcan.
So we need a progressbar that goes from green to red (with ugly mid-green mid-red in middle…)
Please remember following code is in Kotlin
Standard Android ProgressBar can be set to value 0-100, by using
Let’s keep it, all we need is ProgressBar to set color according to this value, so we don’t have to change our other code where ProgressBar is used.
Let’s create new class extending Progres Bar
And use it in Layout
For now, it acts exactly like standard ProgressBar, so how to make it do what we want?
Let’s override setProgress
method :)
All I’ve done here is taking current ProgressDrawable, and set color to value I get from translateValueToColor
I’m setting RGB values (not variables :) ) accordingly to value so value == 0
gets all green and value == 100
gets all red.
And result can look like that:
If you need more specific behaviour or different colors, all you need to do is change translateValueToColor method, by using if statement or anything you’ll find suitable for your case.
Hope you enjoyed this quite short tutorial, be prepared for more :]