In our application we need an indeterminate progress bar, like so:
We can achieve this by setting a negative margin on the ProgressBar, like this:
<ProgressBar
android:id="@+id/progressbar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:indeterminate="true"
android:marginTop="-7dp"
android:visibility="@{loading ? View.VISIBLE : View.GONE}" />
BUT because ConstraintLayout does not support negative margins, it will look like this:
OK, the negative margin was a hack. Let's replace it with a different hack, shall we? Let's introduce our custom view CustomProgressBar
, which extends ProgressBar
and overrides its onDraw
method, like this:
@Override
protected void onDraw(Canvas canvas) {
int marginTop = dpToPx(7);
canvas.translate(0, -marginTop);
super.onDraw(canvas);
}
But all of this smells like bad code. There has to be a better solution! What would you recommend?
Another way to do this is to use a Guideline and center ProgressBar between the parent top and the guideline.
I encountered the same problem as well. And like you said, I come across numerous solutions which all seem like a hack that might break something else down the line. With that said, I came across one solution which is to use this library instead for progress bar.
One thing to note is, it tells you to integrate it by adding:
However, when I used this, it gave me an error from an Android support library for Floating Action Bar. So I'll recommend you to use this instead:
A sample code snippet on how I used it:
Hope this helps!
A dirty workaround I did was set the height of the ProgressBar closely to the to stroke width like so:
Progress bar:
Progress drawable:
Which looked like this:
Solution that feels less like a hack: Wrap a huge
ProgressBar
in a smallerFrameLayout
. That way theFrameLayout
constrains its height, but theProgressBar
still shows in full.