3

I'm trying to make a custom ProgressBar the way I did custom layouts a lot before. This time I'm having issues.

I can achieve the desired look with just this xml:

<ProgressBar
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:indeterminateOnly="false"
    android:progressDrawable="@drawable/progress_bar" />

The ultimate goal, however, would be doing some of the customization in the custom class so the xml shrinks to this:

<se.my.viktklubb.app.progressbar.HorizontalProgressBar
    android:id="@+id/planProgressBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

Here is the custom class:

class HorizontalProgressBar : ProgressBar {

    constructor(context: Context) : super(context) {
        initialSetup()
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        initialSetup()
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        initialSetup()
    }

    fun initialSetup() {
        max = 100
        isIndeterminate = false
        progressDrawable = context.getDrawable(R.drawable.progress_bar)
    }
}

Second constructor gets fired but the bar isn't styled. It actually appears as indeterminate spinning progress and none of these setup gets applied eventually - feels like those are overriden later by something else.

What's wrong here?

DISCLAIMER: This is a very simple example. I'm perfectly aware I could go for styles or a simple xml implementation but I just use this simple case only to demonstrate the issue.

1 Answer 1

0

According to the bullet 5 of this article, you may need to modify initialSetup:

fun initialSetup() {
    max = 100
    isIndeterminate = false
    progressDrawable = context.getDrawable(R.drawable.progress_bar)
    invalidate()
    requestLayout()
}

If it doesn't change anything, try calling initialSetup later, on onResume of activity/fragment for example. If this work, the problem is maybe linked to the complexity of initialization/lifecycle of android components.

Sign up to request clarification or add additional context in comments.

1 Comment

Link is dead. :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.