Tuesday, June 16, 2009

How to create a custom progress bar

First you need to create a progress bar layout file. Let's call it my_custom_pb.xml

<
layer-list xmlns:android="http://schemas.android.com/apk/res/android">


<item android:id="@android:id/background" android:drawable="@drawable/mybg"/>


<item android:id="@android:id/secondaryProgress">
<clip>
<shape>
<corners android:radius="5dip" />
<gradient
android:startColor="#80d3ff00"
android:centerColor="#80b6ff00"
android:centerY="0.75"
android:endColor="#a0cbff00"
android:angle="270"
/>

</shape>
</clip>
</item>

<item android:id="@android:id/progress">
<clip android:drawable="@drawable/myprogress"/>
</item>
</layer-list>

Notice you can either use a simple 9 patch drawable or make your own custom shape!
Then you would add that custom progress bar to the layout you want that bar to appear:

<ProgressBar
android:id="@+id/mypb"
android:layout_width="120px"
android:layout_height="10px"
android:progressDrawable="@drawable/my_custom_pb"
android:max="5"
android:progress="1" />

And finally you would access it from your code like you would with any regular progress bar:

myProgress = (ProgressBar)findViewById(R.id.mypb);
myProgress.setProgress((int)value);
--
Special Thx to Mikael for this one.

3 comments:

  1. Hi, I am new to Android and this was rather appealing to me when I read the tytle, and I believe it was a good post.

    Although when I tried it myself I couldn't quite make it work since the xml work is explicit and done but the examples are not concrete, for instance : @drawable/mybg , @drawable/my_custom_pb.

    I believe you are assuming everyone in your blog has some level of experience with android, but I am here defending the poor little guy who has just started out (ME :) ).

    I would suggest your post to be seperated into 2 parts:

    1- the thing you want to talk about
    2- the explanation for the newbies with a disclamer stating that if the reader understood the code it should skip this part.

    Other than that I repeat, really nice post. Thanks in advance for taking the time to read my post and consider it,
    Toni

    ReplyDelete
  2. Sorry for the late reply.
    Hopefully these links might help you:
    http://blog.mediarain.com/2011/04/android-custom-progressbar-with-rounded-corners/
    http://developer.android.com/reference/android/widget/ProgressBar.html

    ReplyDelete