Android : How to change progress bar color at runtime programmatically?

I faced this problem while creating one of my android applications(in fact, it is my first application :) ). Lets consider we want to create an android application to calculate the commitments progress of a certain category for http://area51.stackexchange.com/ website (note we will display a progress bar with one color red or green for simplicity).

Each time we run this application it calculate the commitment percentage and display a red progress bar if it is less than 50% or green one if it equal or greater than 50%. For learning purpose we will insert the number of total required committed users and the number of committed users and calculate the progress of commitment process.

Now lets write our code. If it is your first android application you can refer to this post to know how to create an android application.
      

How to create the full layout of this simple application is beyond this post, we will concentrate on the progress bar. The following code snippet is the definition of a progress bar and setting its properties in the layout xml file of the main activity
<progressbar 
   android:id="@+id/myprogressbar" 
   android:layout_alignparenttop="true" 
   android:layout_centerhorizontal="true" 
   android:layout_height="wrap_content" 
   android:layout_margin="20dp" 
   android:layout_width="fill_parent" 
   android:max="100" 
   style="android: attr/progressBarStyleHorizontal;
"/>
android:max is the max value of the progress bar and we set its style with the built-in android style of horizontal progress bar.

To change the progress bar with colors you want you need to create a layer-list xml file and save it into res/drawable folder of your project. This xml file will contains the new style of the progress bar that will be attached to it at run time.
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@android:id/background">
        <shape>
            <gradient
                    android:startColor="#000001"
                    android:centerColor="#0b131e"
                    android:centerY="0.75"
                    android:endColor="#0d1522"
                    android:angle="270"
            />
        </shape>
    </item>
    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <gradient
                    android:startColor="#00ff00"
                    android:centerColor="#00dd00"
                    android:centerY="0.75" 
                    android:endColor="#00bb00"
                    android:angle="270"
                />
            </shape>
        </clip>
    </item>
</layer-list>
This is the new drawable of the red progress bar, you can replace values with red font with the color you want. In our example you need to create another one for green progress bar.(In the end of this post there is a link for downloading the full project of this example).

Now we prepared the required files that we need to change the progress bar color and it is time to apply this new style programmatically when the user click the calculate button.
public void Calculate(View view)
{
  if(view.getId()==R.id.btncalc)
  {
     EditText etcomusers = (EditText)findViewById(R.id.comusersnumber);
     double commiteduser =Double.parseDouble(etcomusers.getText().toString());
      
     EditText ettotcomusers = (EditText)findViewById(R.id.totalcomusersnumber);
     double totalcommiteduser =Double.parseDouble(ettotcomusers.getText().toString());
      
    int percent = (int) ((commiteduser/totalcommiteduser)*100);
      
    ProgressBar myprogressbar = (ProgressBar)findViewById(R.id.myprogressbar);
      
    Resources res = getResources();
    Rect bounds = myprogressbar.getProgressDrawable().getBounds();
      
    if(percent >= 50)
    {
     myprogressbar.setProgressDrawable(res.getDrawable(R.drawable.greenprogressbar));
    }
    else
    {
     myprogressbar.setProgressDrawable(res.getDrawable(R.drawable.redprogressbar));
    }
    myprogressbar.getProgressDrawable().setBounds(bounds);
    myprogressbar.setProgress(percent);
  }
}

first section of code for getting the entered values and calculate the committed users percentage. Before changing the progress bar color we need to get the Bounds of the current progress drawable to be applied after setting the new ProgressDrawable with new color. If comitted users percentage is greater than 50% we set the ProgressDrawable with the green one else we set it with the red then we set the Bounds and Progress of the progress bar(the length of colored bar).

You can download sample code here

Comments

  1. i tried this code on on create, all the value i had set properly and, follow exactly the same thing u did, but my progress bar just did not show progress....it show me entire black bar....

    ReplyDelete
  2. need your guidance urgently!
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.challenge_progress);

    UnderControlDb db = new UnderControlDb(getApplicationContext());
    int tA = db.ChallengeGetTargetAmount();
    int tracking = db.ChallengeGetTrackingAmount();
    String spName = db.ChallengeGetCurrentSPName();
    int percent = (int) ((tracking/tA)*100);
    TextView tv = (TextView) findViewById(R.id.tvChallengSPName);
    TextView tv1 = (TextView) findViewById(R.id.tvProgressIndex);
    tv.setText("Challenge for " + spName +" plan");

    ProgressBar myprogressbar = (ProgressBar)findViewById(R.id.myprogressbar);
    Resources res = getResources();
    Rect bounds = myprogressbar.getProgressDrawable().getBounds();
    if(percent >= 50)
    {
    myprogressbar.setProgressDrawable(res.getDrawable(R.drawable.greenprogressbar));
    }
    else
    {
    myprogressbar.setProgressDrawable(res.getDrawable(R.drawable.redprogressbar));
    }
    myprogressbar.getProgressDrawable().setBounds(bounds);
    myprogressbar.setProgress(percent);
    tv1.setText(tracking + "/" + tA);
    }

    i can get all the value, but the progress bar just showing black color.....
    please reply me at jiunhaw924@hotmail.com

    ReplyDelete
    Replies
    1. don't start projects you cannot finish in time. so typical for asians.

      Delete
    2. me too get all the value but the progress color is not showing

      Delete
  3. Valuable post.. Thank you so much

    ReplyDelete

Post a Comment

Popular posts from this blog

ASP.Net MVC : ActionLink with bootstrap icon

ASP.Net MVC : Conditional Validation using ValidationAttribute