Search code examples
androidcolorsprogress-bar

Change progressbar color through CODE ONLY in Android


I have a progressBar using the ProgressBar class.

Just doing this:

progressBar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);

I need to change the color of that one, using input value like so:

int color = "red in RGB value".progressBar.setColor(color)

or something like that...

I can't use an XML layout because the progress bar is customizable for users.


Solution

  • As I found help on a topic here but can't remember the link, I'm posting my full solution which works great for my needs:

        // Draw a simple progressBar from xml
        progressBar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
    
        // Convert the color (Decimal value) to HEX value: (e.g: #4b96a0)
        String color = colorDecToHex(75, 150, 160);
    
        // Define a shape with rounded corners
        final float[] roundedCorners = new float[] { 5, 5, 5, 5, 5, 5, 5, 5 };
        ShapeDrawable pgDrawable = new ShapeDrawable(new RoundRectShape(roundedCorners,     null, null));
    
        // Sets the progressBar color
        pgDrawable.getPaint().setColor(Color.parseColor(color));
    
        // Adds the drawable to your progressBar
        ClipDrawable progress = new ClipDrawable(pgDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL);
        progressBar.setProgressDrawable(progress);
    
        // Sets a background to have the 3D effect
        progressBar.setBackgroundDrawable(Utils.getActivity().getResources()
                .getDrawable(android.R.drawable.progress_horizontal));
    
        // Adds your progressBar to your layout
        contentLayout.addView(progressBar);
    

    And here is the code to convert DECIMAL color values to HEXADECIMAL:

    public static String colorDecToHex(int p_red, int p_green, int p_blue)
    {
        String red = Integer.toHexString(p_red);
        String green = Integer.toHexString(p_green);
        String blue = Integer.toHexString(p_blue);
    
        if (red.length() == 1)
        {
            red = "0" + red;
        }
        if (green.length() == 1)
        {
            green = "0" + green;
        }
        if (blue.length() == 1)
        {
            blue = "0" + blue;
        }
    
        String colorHex = "#" + red + green + blue;
        return colorHex;
    }
    

    I think the last method is not that clean but it works well.

    Hope this well help, too much time wasted on this progressbar.