I want to create a dynamic intermittent progress bar (as illustrated in the image below), that will change its intervals depending on the user's choice, in Android Studio.
The idea is that the user will choose how many times he wishes to do a behavior, and then the bar will fragment accordingly. Then each time they do the behavior, the bar will color a step increment, as shown in the image below.
I am looking for some general guidance on how to do it, since I am new to this.
I have thought of 3 ways to do this:
Have a ton of png. drawables or vectors for each case, and use one accordingly in an Image View. (seems kind of stupid to me)
Create as many views as are the intervals, and then change the view colors accordingly (in this case there will be a problem with the dynamic part of it i.e. interval variability)
Customize somehow a horizontal ProgressBar to do this automatically.
I have searched the internet for the third way which is the most elegant to me, but cant find an answer.
Thank you for your time.
This is actually trivial to obtain using the current ProgressBar
APIs.
Depending on the number of tasks required and number of tasks done, you can update a ProgressBar
using setMax
and setProgress
progressBar.setMax(totalTasks);
progressBar.setProgress(tasksDone);
This will cover a fraction tasksDone / totalTasks
in the progressBar.
Edit: Based on the scenario highlighted in the comments, you can simply use multiple views in a LinearLayout
.
You can use a LinearLayout with the background of the partition color you want.
<LinearLayout
....
android:orientation="horizontal"
android:background="@color/partition"
....
/>
And then simply add the child views programmatically with equal weights (and a horizontal margin):-
for(task in tasks) {
val progressBar = View(this)
progressBar.marginEnd = gapRequired
// customize your view here: Set background, shape etc.
// Set the width to 0 and weight to 1f
val params = LinearLayout.LayoutParams(0, height, 1f)
linearLayout.addView(view, index, params)
}
Later to modify an individual view (fragment of progress bar):-
val view = linearLayout.getChildAt(index)
// Modify the view as needed
To remove a view from the layout:-
linearLayout.removeViewAt(index)
Or if you have the view referenced:-
linearLayout.removeView(view)
You can also remove all views (if you need to reset the entire progress bar for some reason) using linearLayout.removeAllViews()
You might want to use RecyclerView
with an adapter if you are expecting a lot of these fragments in your progressBar.