Search code examples
androidandroid-progressbar

How to Customize a Progress Bar In Android


I am working on an app in which I want to show a ProgressBar, but I want to replace the default Android ProgressBar.

So how can I customize the ProgressBar?

Do I need some graphics and animation for that?

I read the following post but could not get it to work:

Custom Progress bar Android


Solution

  • Customizing a ProgressBar requires defining the attribute or properties for the background and progress of your progress bar.

    Create an XML file named customprogressbar.xml in your res->drawable folder:

    custom_progressbar.xml

    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    
        <!-- Define the background properties like color etc -->
        <item android:id="@android:id/background">
        <shape>
            <gradient
                    android:startColor="#000001"
                    android:centerColor="#0b131e"
                    android:centerY="1.0"
                    android:endColor="#0d1522"
                    android:angle="270"
            />
        </shape>
       </item>
    
      <!-- Define the progress properties like start color, end color etc -->
      <item android:id="@android:id/progress">
        <clip>
            <shape>
                <gradient
                    android:startColor="#007A00"
                    android:centerColor="#007A00"
                    android:centerY="1.0"
                    android:endColor="#06101d"
                    android:angle="270"
                />
            </shape>
        </clip>
        </item>
    </layer-list> 
    

    Now you need to set the progressDrawable property in customprogressbar.xml (drawable)

    You can do this in the XML file or in the Activity (at run time).

    Do the following in your XML:

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleHorizontal"
        android:progressDrawable="@drawable/custom_progressbar"         
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    

    At run time do the following

    // Get the Drawable custom_progressbar                     
        Drawable draw=res.getDrawable(R.drawable.custom_progressbar);
    // set the drawable as progress drawable
        progressBar.setProgressDrawable(draw);
    

    Edit: corrected xml layout