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?
Solution that feels less like a hack: Wrap a huge ProgressBar
in a smaller FrameLayout
. That way the FrameLayout
constrains its height, but the ProgressBar
still shows in full.
<FrameLayout
android:layout_width="match_parent"
android:layout_height="4dp">
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="32dp"
android:layout_gravity="center" />
</FrameLayout>