AndroidDev
AndroidDev

Reputation: 16385

Android Progress Bar Listener

Is there anyway to know when a progressbar has reached it maximum. Like a Listener then could plug into the ProgressBar and lets us know that the progress bar is at the maximum level ?

Kind Regards

Upvotes: 3

Views: 12117

Answers (4)

Raphael C
Raphael C

Reputation: 2402

I think overall you should never have to do this. Is there just one valid case where you need to listen to a progressbar progress? I mean, usually it's the other way around: you set the progressbar progress based on something, not the other way around, so you need to track the progress of that something instead of listening to a view (which may or may not exist by the way).

Upvotes: 0

nicolas asinovich
nicolas asinovich

Reputation: 3511

If you need onProgressChanged like SeekBar - create custom progress (Kotlin):

class MyProgressBar : ProgressBar {

    private var listener: OnMyProgressBarChangeListener? = null

    fun setOnMyProgressBarChangeListener(l: OnMyProgressBarChangeListener) {
        listener = l
    }

    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(
        context,
        attrs
    )

    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int
    ) : super(context, attrs, defStyleAttr)

    override fun setProgress(progress: Int) {
        super.setProgress(progress)
        listener?.onProgressChanged(this)
    }

    interface OnMyProgressBarChangeListener {
        fun onProgressChanged(myProgressBar: MyProgressBar?)
    }

}

And for example in your fragment:

 progress_bar?.setOnMyProgressBarChangeListener(object :
            MyProgressBar.OnMyProgressBarChangeListener {
            override fun onProgressChanged(myProgressBar: MyProgressBar?) {
                val p = progress_bar.progress
                // do stuff like this
                if (p != 100) {
                    percentCallback?.changePercent(p.toString()) // show animation custom view with grow percents
                } else {
                    shieldView.setFinishAndDrawCheckMark() // draw check mark
                }
            }
        })

Upvotes: 1

Robb1
Robb1

Reputation: 5025

I think the cleanest way would be just adding this to your code:

 if (progressBar.getProgress() == progressBar.getMax()) {
     // do stuff you need
 }

Upvotes: 1

Leon Lucardie
Leon Lucardie

Reputation: 9730

There isn't a direct way to do this. A workaround could be to make a custom implementation of the ProgressBar and override the setProgress method:

public MyProgressBar extends ProgressBar
{
   @Override
   public void setProgress(int progress)
   {
       super.setProgress(progress);
       if(progress == this.getMax())
       {
           //Do stuff when progress is max
       }
   }
}

Upvotes: 11

Related Questions