Как изменить цвет прогресс бара

Поменять цвет ProgressBar C# Решение и ответ на вопрос 247557
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
 
namespace System.Windows.Form
{
    [Description("Color Progress Bar")]
    [ToolboxBitmap(typeof(ProgressBar))]
    [Designer(typeof(ColorProgressBarDesigner))]
    public class ColorProgressBar : System.Windows.Forms.Control
    {   
    
        //
        // set default values
        //
        private int _Value = 0;
        private int _Minimum = 0;
        private int _Maximum = 100;
        private int _Step = 10;
        
        private FillStyles _FillStyle = FillStyles.Solid;
 
        private Color _BarColor = Color.FromArgb(255, 128, 128);
        private Color _BorderColor = Color.Black;
 
        public enum FillStyles
        {
            Solid,
            Dashed
        }
 
        public ColorProgressBar()
        {
            base.Size = new Size(150, 15);
            SetStyle(
                ControlStyles.AllPaintingInWmPaint |
                ControlStyles.ResizeRedraw |
                ControlStyles.DoubleBuffer,
                true
                );
        }
 
        [Description( "ColorProgressBar color")]
        [Category( "ColorProgressBar" )]
        public Color BarColor
        {
            get
            {
                return _BarColor;
            }
            set
            {
                _BarColor = value;
                this.Invalidate();
            }
        }
 
        [Description( "ColorProgressBar fill style")]
        [Category( "ColorProgressBar" )]
        public FillStyles FillStyle
        {
            get
            {
                return _FillStyle;
            }
            set
            {
                _FillStyle = value;
                this.Invalidate();
            }
        }
 
        [Description( "The current value for the ColorProgressBar, in the range specified by the Minimum and Maximum properties." )]
        [Category( "ColorProgressBar" )]
        // the rest of the Properties windows must be updated when this peroperty is changed.
        [RefreshProperties(RefreshProperties.All)]
        public int Value
        {
            get
            {
                return _Value;
            }
            set
            {
                if (value < _Minimum)
                {
                    throw new ArgumentException("'"+value+"' is not a valid value for 'Value'.n"+
                        "'Value' must be between 'Minimum' and 'Maximum'.");
                }
 
                if (value > _Maximum)
                {
                    throw new ArgumentException("'"+value+"' is not a valid value for 'Value'.n"+
                        "'Value' must be between 'Minimum' and 'Maximum'.");
                }
 
                _Value = value;         
                this.Invalidate();
            }
        }
        
        [Description("The lower bound of the range this ColorProgressbar is working with.")]
        [Category("ColorProgressBar")]
        [RefreshProperties(RefreshProperties.All)]
        public int Minimum
        {
            get
            {
                return _Minimum;
            }
            set
            {
                _Minimum = value;
 
                if (_Minimum > _Maximum)
                    _Maximum = _Minimum;
                if (_Minimum > _Value)
                    _Value = _Minimum;
 
                this.Invalidate();
            }
        }
 
        [Description("The uppper bound of the range this ColorProgressbar is working with.")]
        [Category("ColorProgressBar")]
        [RefreshProperties(RefreshProperties.All)]
        public int Maximum
        {
            get
            {
                return _Maximum;
            }
            set
            {
                _Maximum = value;
 
                if (_Maximum < _Value)
                    _Value = _Maximum;
                if (_Maximum < _Minimum)
                    _Minimum = _Maximum;
 
                this.Invalidate();
            }
        }
 
        [Description("The amount to jump the current value of the control by when the Step() method is called.")]
        [Category("ColorProgressBar")]      
        public int Step
        {
            get
            {
                return _Step;
            }
            set
            {
                _Step = value;
                this.Invalidate();
            }
        }
 
        [Description("The border color of ColorProgressBar")]
        [Category("ColorProgressBar")]      
        public Color BorderColor
        {
            get
            {
                return _BorderColor;
            }
            set
            {
                _BorderColor = value;
                this.Invalidate();
            }
        }
        
        //
        // Call the PerformStep() method to increase the value displayed by the amount set in the Step property
        //
        public void PerformStep()
        {
            if (_Value < _Maximum)
                _Value += _Step;
            else
                _Value = _Maximum;
 
            this.Invalidate();
        }
        
        //
        // Call the PerformStepBack() method to decrease the value displayed by the amount set in the Step property
        //
        public void PerformStepBack()
        {
            if (_Value > _Minimum)
                _Value -= _Step;
            else
                _Value = _Minimum;
 
            this.Invalidate();
        }
 
        //
        // Call the Increment() method to increase the value displayed by an integer you specify
        // 
        public void Increment(int value)
        {
            if (_Value < _Maximum)
                _Value += value;
            else
                _Value = _Maximum;
 
            this.Invalidate();
        }
        
        //
        // Call the Decrement() method to decrease the value displayed by an integer you specify
        // 
        public void Decrement(int value)
        {
            if (_Value > _Minimum)
                _Value -= value;
            else
                _Value = _Minimum;
 
            this.Invalidate();
        }
        
        protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
        {
            //
            // Calculate matching colors
            //
            Color darkColor = ControlPaint.Dark(_BarColor);
            Color bgColor = ControlPaint.Dark(_BarColor);
 
            //
            // Fill background
            //
            SolidBrush bgBrush = new SolidBrush(bgColor);
            e.Graphics.FillRectangle(bgBrush, this.ClientRectangle);
            bgBrush.Dispose();
            
            // 
            // Check for value
            //
            if (_Maximum == _Minimum || _Value == 0)
            {
                // Draw border only and exit;
                drawBorder(e.Graphics);
                return;
            }
 
            //
            // The following is the width of the bar. This will vary with each value.
            //
            int fillWidth = (this.Width * _Value) / (_Maximum - _Minimum);
            
            //
            // GDI+ doesn't like rectangles 0px wide or high
            //
            if (fillWidth == 0)
            {
                // Draw border only and exti;
                drawBorder(e.Graphics);
                return;
            }
 
            //
            // Rectangles for upper and lower half of bar
            //
            Rectangle topRect = new Rectangle(0, 0, fillWidth, this.Height / 2);
            Rectangle buttomRect = new Rectangle(0, this.Height / 2, fillWidth, this.Height / 2);
 
            //
            // The gradient brush
            //
            LinearGradientBrush brush;
 
            //
            // Paint upper half
            //
            brush = new LinearGradientBrush(new Point(0, 0),
                new Point(0, this.Height / 2), darkColor, _BarColor);
            e.Graphics.FillRectangle(brush, topRect);
            brush.Dispose();
 
            //
            // Paint lower half
            // (this.Height/2 - 1 because there would be a dark line in the middle of the bar)
            //
            brush = new LinearGradientBrush(new Point(0, this.Height / 2 - 1),
                new Point(0, this.Height), _BarColor, darkColor);
            e.Graphics.FillRectangle(brush, buttomRect);
            brush.Dispose();
 
            //
            // Calculate separator's setting
            //
            int sepWidth = (int)(this.Height * .67);
            int sepCount = (int)(fillWidth / sepWidth);
            Color sepColor = ControlPaint.LightLight(_BarColor);
 
            //
            // Paint separators
            //
            switch (_FillStyle)
            {
                case FillStyles.Dashed:
                    // Draw each separator line
                    for (int i = 1; i <= sepCount; i++)
                    {
                        e.Graphics.DrawLine(new Pen(sepColor, 1),
                            sepWidth * i, 0, sepWidth * i, this.Height);
                    }
                    break;
 
                case FillStyles.Solid:
                    // Draw nothing
                    break;
 
                default:
                    break;
            }
 
            //
            // Draw border and exit
            //
            drawBorder(e.Graphics);
        }
 
        //
        // Draw border
        //
        protected void drawBorder(Graphics g)
        {
            Rectangle borderRect = new Rectangle(0, 0,
                ClientRectangle.Width - 1, ClientRectangle.Height - 1);
            g.DrawRectangle(new Pen(_BorderColor, 1), borderRect);
        }
    }
}

Asked
13 years, 1 month ago

Viewed
754k times

I’m using an horizontal progress bar in my Android application, and I want to change its progress color (which is Yellow by default). How can I do it using code (not XML)?

Mahozad's user avatar

Mahozad

15.3k11 gold badges101 silver badges119 bronze badges

asked Jan 7, 2010 at 14:13

WhiteTigerK's user avatar

4

For a horizontal ProgressBar, you can use a ColorFilter, too, like this:

progressBar.getProgressDrawable().setColorFilter(
    Color.RED, android.graphics.PorterDuff.Mode.SRC_IN);

Red ProgressBar using color filter

Note: This modifies the appearance of all progress bars in your app. To only modify one specific progress bar, do this:

Drawable progressDrawable = progressBar.getProgressDrawable().mutate();
progressDrawable.setColorFilter(Color.RED, android.graphics.PorterDuff.Mode.SRC_IN);
progressBar.setProgressDrawable(progressDrawable);

If progressBar is indeterminate then use getIndeterminateDrawable() instead of getProgressDrawable().

Since Lollipop (API 21) you can set a progress tint:

progressBar.setProgressTintList(ColorStateList.valueOf(Color.RED));

Red ProgressBar using progress tint

answered Apr 4, 2013 at 11:25

Torben Kohlmeier's user avatar

Torben KohlmeierTorben Kohlmeier

6,6231 gold badge15 silver badges15 bronze badges

16

This is not programmatically but I think it could help a lot of people anyway.
I tried a lot and the most efficient way was to add this lines to my ProgressBar in the .xml File:

            android:indeterminate="true"
            android:indeterminateTintMode="src_atop"
            android:indeterminateTint="@color/secondary"

So in the end this code did it for me:

<ProgressBar
            android:id="@+id/progressBar"
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:layout_marginTop="50dp"
            android:layout_marginBottom="50dp"
            android:visibility="visible"
            android:indeterminate="true"
            android:indeterminateTintMode="src_atop"
            android:indeterminateTint="@color/secondary">

This solution works for API 21+

Vadim Kotov's user avatar

Vadim Kotov

7,9648 gold badges48 silver badges62 bronze badges

answered Jul 11, 2015 at 16:04

FFirmenich's user avatar

FFirmenichFFirmenich

5,4511 gold badge17 silver badges28 bronze badges

6

I’m sorry that it’s not the answer, but what’s driving the requirement setting it from code ?
And .setProgressDrawable should work if it’s defined correctly

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

<item android:id="@android:id/background">
    <shape>
        <corners android:radius="5dip" />
        <gradient
                android:startColor="#ff9d9e9d"
                android:centerColor="#ff5a5d5a"
                android:centerY="0.75"
                android:endColor="#ff747674"
                android:angle="270"
        />
    </shape>
</item>

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

<item android:id="@android:id/progress">
    <clip>
        <shape>
            <corners
                android:radius="5dip" />
            <gradient
                android:startColor="@color/progress_start"
                android:endColor="@color/progress_end"
                android:angle="270" 
            />
        </shape>
    </clip>
</item>

</layer-list>

WarrenFaith's user avatar

WarrenFaith

57.3k25 gold badges134 silver badges148 bronze badges

answered Jan 7, 2010 at 15:00

Alex Volovoy's user avatar

Alex VolovoyAlex Volovoy

67.5k13 gold badges73 silver badges54 bronze badges

11

For my indeterminate progressbar (spinner) I just set a color filter on the drawable. Works great and just one line.

Example where setting color to red:

ProgressBar spinner = new android.widget.ProgressBar(
                context,
                null,
                android.R.attr.progressBarStyle);

spinner.getIndeterminateDrawable().setColorFilter(0xFFFF0000, android.graphics.PorterDuff.Mode.MULTIPLY);

enter image description here

answered Jun 7, 2012 at 9:14

jhavatar's user avatar

jhavatarjhavatar

3,2061 gold badge17 silver badges11 bronze badges

5

This is an old question, but using theme is not mentioned here. If your default theme is using AppCompat, your ProgressBar‘s color will be colorAccent you have defined.

Changing colorAccent will also change your ProgressBar‘s color, but there changes also reflects at multiple places. So, if you want a different color just for a specific PregressBar you can do that by applying theme to that ProgressBar :

  • Extend your default theme and override colorAccent

    <style name="AppTheme.WhiteAccent">
        <item name="colorAccent">@color/white</item> <!-- Whatever color you want-->
    </style>
    
  • And in ProgressBar add the android:theme attribute:

    android:theme="@style/AppTheme.WhiteAccent"
    

So it will look something like this:

<ProgressBar
        android:id="@+id/loading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:padding="10dp"
        android:theme="@style/AppTheme.WhiteAccent" />

So you are just changing a colorAccent for your particular ProgressBar.

Note: Using style will not work. You need to use android:theme only.
You can find more use of theme here: https://plus.google.com/u/0/+AndroidDevelopers/posts/JXHKyhsWHAH

answered Jul 9, 2016 at 13:08

kirtan403's user avatar

kirtan403kirtan403

7,1476 gold badges52 silver badges95 bronze badges

9

All API

if use all API just create the theme in style

style.xml

<resources>

    //...

    <style name="progressBarBlue" parent="@style/Theme.AppCompat">
        <item name="colorAccent">@color/blue</item>
    </style>

</resources>

and use in progress

<ProgressBar
    ...
    android:theme="@style/progressBarBlue" />

API level 21 and higher

if used in API level 21 and higher just use this code:

<ProgressBar
   //...
   android:indeterminate="true"
   android:indeterminateTintMode="src_atop"
   android:indeterminateTint="@color/secondary"/>

answered Sep 24, 2018 at 14:03

Rasoul Miri's user avatar

Rasoul MiriRasoul Miri

10.2k1 gold badge64 silver badges75 bronze badges

1

This works for me. It also works for lower version too. Add this to your syles.xml

<style name="ProgressBarTheme" parent="ThemeOverlay.AppCompat.Light">
<item name="colorAccent">@color/colorPrimary</item>
</style>

And use it like this in xml

<ProgressBar
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:theme="@style/ProgressBarTheme"
   />

answered Sep 25, 2019 at 5:39

Devinder Jhinjer's user avatar

3

This worked for me :

<ProgressBar
 android:indeterminateTint="#d60909"
 ... />

answered Jul 6, 2017 at 5:40

MOH3N's user avatar

MOH3NMOH3N

8859 silver badges14 bronze badges

1

as per some of the suggestions, you CAN specify a shape and clipdrawable with a colour, then set it. I have this working programatically. This is how I do it..

First make sure you import the drawable library..

import android.graphics.drawable.*;

Then use the code similar to below;

ProgressBar pg = (ProgressBar)row.findViewById(R.id.progress);
final float[] roundedCorners = new float[] { 5, 5, 5, 5, 5, 5, 5, 5 };
pgDrawable = new ShapeDrawable(new RoundRectShape(roundedCorners, null,null));
String MyColor = "#FF00FF";
pgDrawable.getPaint().setColor(Color.parseColor(MyColor));
ClipDrawable progress = new ClipDrawable(pgDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL);
pg.setProgressDrawable(progress);   
pg.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.progress_horizontal));
pg.setProgress(45);

answered Mar 6, 2011 at 9:46

PaulieG's user avatar

PaulieGPaulieG

3413 silver badges2 bronze badges

6

if Indeterminate:

((ProgressBar)findViewById(R.id.progressBar))
    .getIndeterminateDrawable()
    .setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);

Paweł Tomkiel's user avatar

answered Mar 22, 2015 at 17:24

the.knife's user avatar

the.knifethe.knife

4094 silver badges3 bronze badges

1

android:progressTint="#ffffff" 

answered Sep 14, 2016 at 13:32

Paul's user avatar

PaulPaul

7741 gold badge9 silver badges15 bronze badges

0

Nowadays in 2016 I found some pre-Lollipop devices don’t honour the colorAccent setting, so my final solution for all APIs is now the following:

// fixes pre-Lollipop progressBar indeterminateDrawable tinting
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {

    Drawable wrapDrawable = DrawableCompat.wrap(mProgressBar.getIndeterminateDrawable());
    DrawableCompat.setTint(wrapDrawable, ContextCompat.getColor(getContext(), android.R.color.holo_green_light));
    mProgressBar.setIndeterminateDrawable(DrawableCompat.unwrap(wrapDrawable));
} else {
    mProgressBar.getIndeterminateDrawable().setColorFilter(ContextCompat.getColor(getContext(), android.R.color.holo_green_light), PorterDuff.Mode.SRC_IN);
}

For bonus points, it doesn’t use any deprecated code. Try it!

answered Sep 14, 2016 at 10:31

Henrique de Sousa's user avatar

2

For SDK ver 21 and above

android:indeterminateTint="@color/orange"

in XML Works for me, is easy enough.

answered Apr 21, 2017 at 12:38

Mughil's user avatar

MughilMughil

6856 silver badges8 bronze badges

1

Trust me, the easiest solution is just paste this inside progressBar :

android:indeterminateTint="@android:color/white"

answered Nov 8, 2021 at 15:42

A.I.Shakil's user avatar

A.I.ShakilA.I.Shakil

7354 silver badges18 bronze badges

THis is what i did. Worked.

ProgressBar:

<ProgressBar
            android:id="@+id/progressBar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="4"
            android:indeterminateDrawable="@drawable/progressdrawable"
           />

progressdrawable.xml:
Here use gradient to change colour as you like. And android:toDegrees=»X» increse the value of X and progressbar rotate fast. Decrease and it rotate slow.Customize according to your needs.

<?xml version="1.0" encoding="utf-8"?>
     <rotate xmlns:android="http://schemas.android.com/apk/res/android"
            android:duration="4000"
            android:fromDegrees="0"
            android:pivotX="50%"
            android:pivotY="50%"
            android:toDegrees="360" >

            <shape
                android:innerRadius="20dp"
                android:shape="ring"
                android:thickness="4dp"
                android:useLevel="false" >
                <size
                    android:height="48dp"
                    android:width="48dp" />

                <gradient
                    android:centerColor="#80ec7e2a"
                    android:centerY="0.5"
                    android:endColor="#ffec7e2a"
                    android:startColor="#00ec7e2a"
                    android:type="sweep"
                    android:useLevel="false" />
            </shape>

        </rotate>

sample:
enter image description here

answered Jan 31, 2018 at 6:44

Debasish Ghosh's user avatar

1

Add in ProgressBar inside of Xml

For SDK ver 21 and above

android:indeterminateTint="@color/red"

answered Jun 23, 2021 at 3:04

Mark Nashat's user avatar

Mark NashatMark Nashat

5907 silver badges8 bronze badges

2

Hit the same problem while working on modifying the look/feel of the default progress bar. Here is some more info that will hopefully help people :)

  • The name of the xml file must only contain characters: a-z0-9_. (ie. no capitals!)
  • To reference your «drawable» it is R.drawable.filename
  • To override the default look, you use myProgressBar.setProgressDrawable(...), however you need can’t just refer to your custom layout as R.drawable.filename, you need to retrieve it as a Drawable:
    Resources res = getResources();
    myProgressBar.setProgressDrawable(res.getDrawable(R.drawable.filename);
    
  • You need to set style before setting progress/secondary progress/max (setting it afterwards for me resulted in an ’empty’ progress bar)

answered Feb 28, 2011 at 12:41

pyko's user avatar

pykopyko

3,3595 gold badges25 silver badges31 bronze badges

You can try to change your Styles, Themes, or using android:indeterminateTint=»@color/yourColor» anywhere you want, but there’s just one way o doing that will work on any Android SKD version:

If you progress bar is not indeterminate, please use:

progressBar.getProgressDrawable().setColorFilter(ContextCompat.getColor(context, R.color.yourColor), PorterDuff.Mode.SRC_IN );

If you progress bar is indeterminate, please use:

progressBar.getIndeterminateDrawable().setColorFilter(ContextCompat.getColor(getContext(), R.color.yourColor), PorterDuff.Mode.SRC_IN );

It’s sad that Android is such a mess!

answered Dec 4, 2017 at 16:53

Adriano Moutinho's user avatar

1

How I did it in horizontal ProgressBar:

    LayerDrawable layerDrawable = (LayerDrawable) progressBar.getProgressDrawable();
    Drawable progressDrawable = layerDrawable.findDrawableByLayerId(android.R.id.progress);
    progressDrawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);

answered Dec 16, 2015 at 11:36

mieszk3's user avatar

mieszk3mieszk3

2663 silver badges9 bronze badges

2

There’s probably one thing that hasn’t been referred to in this answer:

If your theme is inheriting from Theme.AppCompat, ProgressBar will assume the color you defined as "colorAccent" in your theme.

So, using..

<item name="colorAccent">@color/custom_color</item>

..will tint the color of the ProgressBar automagically to the @color/custom_color .

answered Jan 21, 2016 at 18:53

Henrique de Sousa's user avatar

1

Simplest Solution if you want to change the colour in the layout xml file, use the below code and use indeterminateTint property for your desired color.

    <ProgressBar
      android:id="@+id/progressBar"
      style="?android:attr/progressBarStyle"
      android:layout_width="wrap_content"
      android:indeterminate="true"
      android:indeterminateTintMode="src_atop"
      android:indeterminateTint="#ddbd4e"
      android:layout_height="wrap_content"
      android:layout_marginBottom="20dp"
      android:layout_alignParentBottom="true"
      android:layout_centerHorizontal="true" />

answered Nov 25, 2017 at 4:27

Naveed Ahmad's user avatar

Naveed AhmadNaveed Ahmad

6,5672 gold badges58 silver badges83 bronze badges

0

The most simple way of changing the foreground and background colour of a progress bar is

<ProgressBar
                        style="@android:style/Widget.ProgressBar.Horizontal"
                        android:id="@+id/pb_main"
                        android:layout_width="match_parent"
                        android:layout_height="8dp"
                        android:progress="30"
                        android:progressTint="#82e9de"
                        android:progressBackgroundTint="#82e9de"
                        />

just add

                        android:progressTint="#82e9de" //for foreground colour
                        android:progressBackgroundTint="#82e9de" //for background colour

answered Apr 18, 2020 at 6:50

Satyam Patil's user avatar

1

This solution worked for me :

<style name="Progressbar.White" parent="AppTheme">
    <item name="colorControlActivated">@color/white</item>
</style>

<ProgressBar
    android:layout_width="@dimen/d_40"
    android:layout_height="@dimen/d_40"
    android:indeterminate="true"
    android:theme="@style/Progressbar.White"/>

Hiroyuki Nuri's user avatar

Hiroyuki Nuri

5,21815 gold badges71 silver badges124 bronze badges

answered Aug 1, 2017 at 13:55

S.Javed's user avatar

S.JavedS.Javed

3303 silver badges7 bronze badges

0

For default ( indeterminate )

add

android:indeterminateTint="@color/white"

for determinate

    android:progressTint="@color/color_1"

    //OR
    progressBar.getProgressDrawable().setColorFilter( PorterDuffColorFilter(Color.RED,android.graphics.PorterDuff.Mode.SRC_IN));

answered Oct 7, 2021 at 9:19

Nasib's user avatar

NasibNasib

1,0181 gold badge11 silver badges22 bronze badges

To change horizontal ProgressBar color (in kotlin):

fun tintHorizontalProgress(progress: ProgressBar, @ColorInt color: Int = ContextCompat.getColor(progress.context, R.color.colorPrimary)){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        progress.progressTintList = ColorStateList.valueOf(color)
    } else{
        val layerDrawable = progress.progressDrawable as? LayerDrawable
        val progressDrawable = layerDrawable?.findDrawableByLayerId(android.R.id.progress)
        progressDrawable?.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
    }
}

To change indeterminate ProgressBar color:

fun tintIndeterminateProgress(progress: ProgressBar, @ColorInt color: Int = ContextCompat.getColor(progress.context, R.color.colorPrimary)){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        progress.indeterminateTintList = ColorStateList.valueOf(color)
    } else {
        (progress.indeterminateDrawable as? LayerDrawable)?.apply {
            if (numberOfLayers >= 2) {
                setId(0, android.R.id.progress)
                setId(1, android.R.id.secondaryProgress)
                val progressDrawable = findDrawableByLayerId(android.R.id.progress).mutate()
                progressDrawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
            }
        }
    }
}

And it finally normally tint pre-lollipop progressBars

tinted progress on api 19

Community's user avatar

answered Apr 5, 2019 at 14:19

John's user avatar

JohnJohn

1,38014 silver badges15 bronze badges

0

One more little thing, the theme solution does work if you inherit a base theme, so for app compact your theme should be:

<style name="AppTheme.Custom" parent="@style/Theme.AppCompat">
    <item name="colorAccent">@color/custom</item>
</style>

And then set this in the progress bar theme

<ProgressBar
    android:id="@+id/progressCircle_progressBar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:theme="@style/AppTheme.Custom"
    android:indeterminate="true"/>

answered May 23, 2017 at 19:27

Calin's user avatar

CalinCalin

6,5815 gold badges47 silver badges79 bronze badges

0

Simply use:

DrawableCompat.setTint(progressBar.getIndeterminateDrawable(),yourColor)

answered May 3, 2020 at 14:15

Amir Hossein Ghasemi's user avatar

1

simply use:

PorterDuff.Mode mode = PorterDuff.Mode.SRC_IN;
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
    mode = PorterDuff.Mode.MULTIPLY;
}

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    progressBar.setProgressTintList(ColorStateList.valueOf(Color.RED));
    progressBar.setProgressBackgroundTintList(ColorStateList.valueOf(Color.RED));
} else {
    Drawable progressDrawable;
    progressDrawable = (progressBar.isIndeterminate() ? progressBar.getIndeterminateDrawable() : progressBar.getProgressDrawable()).mutate();
    progressDrawable.setColorFilter(context.getResources().getColor(Color.RED), mode);
    progressBar.setProgressDrawable(progressDrawable);
}

answered Aug 10, 2019 at 15:57

Mohammad Fneish's user avatar

Mohammad FneishMohammad Fneish

7391 gold badge8 silver badges19 bronze badges

Horizontal progress bar custom material style :

To change color of background and progress of horizontal progress bar.

<style name="MyProgressBar" parent="@style/Widget.AppCompat.ProgressBar.Horizontal">
    <item name="android:progressBackgroundTint">#69f0ae</item>
    <item name="android:progressTint">#b71c1c</item>
    <item name="android:minWidth">200dp</item>
</style>

Apply it to progress bar by setting style attribute, for custom material styles and custom progress bar check http://www.zoftino.com/android-progressbar-and-custom-progressbar-examples

answered Sep 21, 2017 at 14:53

Arnav Rao's user avatar

Arnav RaoArnav Rao

6,5122 gold badges32 silver badges31 bronze badges

1

Use the android.support.v4.graphics.drawable.DrawableCompat:

            Drawable progressDrawable = progressBar.getIndeterminateDrawable();
            if (progressDrawable  != null) {
                Drawable mutateDrawable = progressDrawable.mutate();
                DrawableCompat.setTint(mutateDrawable, primaryColor);
                progressBar.setProgressDrawable(mutateDrawable);
            }

answered Mar 15, 2018 at 13:35

Alécio Carvalho's user avatar

Alécio CarvalhoAlécio Carvalho

13.3k5 gold badges67 silver badges73 bronze badges

Asked
13 years, 1 month ago

Viewed
754k times

I’m using an horizontal progress bar in my Android application, and I want to change its progress color (which is Yellow by default). How can I do it using code (not XML)?

Mahozad's user avatar

Mahozad

15.3k11 gold badges101 silver badges119 bronze badges

asked Jan 7, 2010 at 14:13

WhiteTigerK's user avatar

4

For a horizontal ProgressBar, you can use a ColorFilter, too, like this:

progressBar.getProgressDrawable().setColorFilter(
    Color.RED, android.graphics.PorterDuff.Mode.SRC_IN);

Red ProgressBar using color filter

Note: This modifies the appearance of all progress bars in your app. To only modify one specific progress bar, do this:

Drawable progressDrawable = progressBar.getProgressDrawable().mutate();
progressDrawable.setColorFilter(Color.RED, android.graphics.PorterDuff.Mode.SRC_IN);
progressBar.setProgressDrawable(progressDrawable);

If progressBar is indeterminate then use getIndeterminateDrawable() instead of getProgressDrawable().

Since Lollipop (API 21) you can set a progress tint:

progressBar.setProgressTintList(ColorStateList.valueOf(Color.RED));

Red ProgressBar using progress tint

answered Apr 4, 2013 at 11:25

Torben Kohlmeier's user avatar

Torben KohlmeierTorben Kohlmeier

6,6231 gold badge15 silver badges15 bronze badges

16

This is not programmatically but I think it could help a lot of people anyway.
I tried a lot and the most efficient way was to add this lines to my ProgressBar in the .xml File:

            android:indeterminate="true"
            android:indeterminateTintMode="src_atop"
            android:indeterminateTint="@color/secondary"

So in the end this code did it for me:

<ProgressBar
            android:id="@+id/progressBar"
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:layout_marginTop="50dp"
            android:layout_marginBottom="50dp"
            android:visibility="visible"
            android:indeterminate="true"
            android:indeterminateTintMode="src_atop"
            android:indeterminateTint="@color/secondary">

This solution works for API 21+

Vadim Kotov's user avatar

Vadim Kotov

7,9648 gold badges48 silver badges62 bronze badges

answered Jul 11, 2015 at 16:04

FFirmenich's user avatar

FFirmenichFFirmenich

5,4511 gold badge17 silver badges28 bronze badges

6

I’m sorry that it’s not the answer, but what’s driving the requirement setting it from code ?
And .setProgressDrawable should work if it’s defined correctly

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

<item android:id="@android:id/background">
    <shape>
        <corners android:radius="5dip" />
        <gradient
                android:startColor="#ff9d9e9d"
                android:centerColor="#ff5a5d5a"
                android:centerY="0.75"
                android:endColor="#ff747674"
                android:angle="270"
        />
    </shape>
</item>

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

<item android:id="@android:id/progress">
    <clip>
        <shape>
            <corners
                android:radius="5dip" />
            <gradient
                android:startColor="@color/progress_start"
                android:endColor="@color/progress_end"
                android:angle="270" 
            />
        </shape>
    </clip>
</item>

</layer-list>

WarrenFaith's user avatar

WarrenFaith

57.3k25 gold badges134 silver badges148 bronze badges

answered Jan 7, 2010 at 15:00

Alex Volovoy's user avatar

Alex VolovoyAlex Volovoy

67.5k13 gold badges73 silver badges54 bronze badges

11

For my indeterminate progressbar (spinner) I just set a color filter on the drawable. Works great and just one line.

Example where setting color to red:

ProgressBar spinner = new android.widget.ProgressBar(
                context,
                null,
                android.R.attr.progressBarStyle);

spinner.getIndeterminateDrawable().setColorFilter(0xFFFF0000, android.graphics.PorterDuff.Mode.MULTIPLY);

enter image description here

answered Jun 7, 2012 at 9:14

jhavatar's user avatar

jhavatarjhavatar

3,2061 gold badge17 silver badges11 bronze badges

5

This is an old question, but using theme is not mentioned here. If your default theme is using AppCompat, your ProgressBar‘s color will be colorAccent you have defined.

Changing colorAccent will also change your ProgressBar‘s color, but there changes also reflects at multiple places. So, if you want a different color just for a specific PregressBar you can do that by applying theme to that ProgressBar :

  • Extend your default theme and override colorAccent

    <style name="AppTheme.WhiteAccent">
        <item name="colorAccent">@color/white</item> <!-- Whatever color you want-->
    </style>
    
  • And in ProgressBar add the android:theme attribute:

    android:theme="@style/AppTheme.WhiteAccent"
    

So it will look something like this:

<ProgressBar
        android:id="@+id/loading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:padding="10dp"
        android:theme="@style/AppTheme.WhiteAccent" />

So you are just changing a colorAccent for your particular ProgressBar.

Note: Using style will not work. You need to use android:theme only.
You can find more use of theme here: https://plus.google.com/u/0/+AndroidDevelopers/posts/JXHKyhsWHAH

answered Jul 9, 2016 at 13:08

kirtan403's user avatar

kirtan403kirtan403

7,1476 gold badges52 silver badges95 bronze badges

9

All API

if use all API just create the theme in style

style.xml

<resources>

    //...

    <style name="progressBarBlue" parent="@style/Theme.AppCompat">
        <item name="colorAccent">@color/blue</item>
    </style>

</resources>

and use in progress

<ProgressBar
    ...
    android:theme="@style/progressBarBlue" />

API level 21 and higher

if used in API level 21 and higher just use this code:

<ProgressBar
   //...
   android:indeterminate="true"
   android:indeterminateTintMode="src_atop"
   android:indeterminateTint="@color/secondary"/>

answered Sep 24, 2018 at 14:03

Rasoul Miri's user avatar

Rasoul MiriRasoul Miri

10.2k1 gold badge64 silver badges75 bronze badges

1

This works for me. It also works for lower version too. Add this to your syles.xml

<style name="ProgressBarTheme" parent="ThemeOverlay.AppCompat.Light">
<item name="colorAccent">@color/colorPrimary</item>
</style>

And use it like this in xml

<ProgressBar
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:theme="@style/ProgressBarTheme"
   />

answered Sep 25, 2019 at 5:39

Devinder Jhinjer's user avatar

3

This worked for me :

<ProgressBar
 android:indeterminateTint="#d60909"
 ... />

answered Jul 6, 2017 at 5:40

MOH3N's user avatar

MOH3NMOH3N

8859 silver badges14 bronze badges

1

as per some of the suggestions, you CAN specify a shape and clipdrawable with a colour, then set it. I have this working programatically. This is how I do it..

First make sure you import the drawable library..

import android.graphics.drawable.*;

Then use the code similar to below;

ProgressBar pg = (ProgressBar)row.findViewById(R.id.progress);
final float[] roundedCorners = new float[] { 5, 5, 5, 5, 5, 5, 5, 5 };
pgDrawable = new ShapeDrawable(new RoundRectShape(roundedCorners, null,null));
String MyColor = "#FF00FF";
pgDrawable.getPaint().setColor(Color.parseColor(MyColor));
ClipDrawable progress = new ClipDrawable(pgDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL);
pg.setProgressDrawable(progress);   
pg.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.progress_horizontal));
pg.setProgress(45);

answered Mar 6, 2011 at 9:46

PaulieG's user avatar

PaulieGPaulieG

3413 silver badges2 bronze badges

6

if Indeterminate:

((ProgressBar)findViewById(R.id.progressBar))
    .getIndeterminateDrawable()
    .setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);

Paweł Tomkiel's user avatar

answered Mar 22, 2015 at 17:24

the.knife's user avatar

the.knifethe.knife

4094 silver badges3 bronze badges

1

android:progressTint="#ffffff" 

answered Sep 14, 2016 at 13:32

Paul's user avatar

PaulPaul

7741 gold badge9 silver badges15 bronze badges

0

Nowadays in 2016 I found some pre-Lollipop devices don’t honour the colorAccent setting, so my final solution for all APIs is now the following:

// fixes pre-Lollipop progressBar indeterminateDrawable tinting
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {

    Drawable wrapDrawable = DrawableCompat.wrap(mProgressBar.getIndeterminateDrawable());
    DrawableCompat.setTint(wrapDrawable, ContextCompat.getColor(getContext(), android.R.color.holo_green_light));
    mProgressBar.setIndeterminateDrawable(DrawableCompat.unwrap(wrapDrawable));
} else {
    mProgressBar.getIndeterminateDrawable().setColorFilter(ContextCompat.getColor(getContext(), android.R.color.holo_green_light), PorterDuff.Mode.SRC_IN);
}

For bonus points, it doesn’t use any deprecated code. Try it!

answered Sep 14, 2016 at 10:31

Henrique de Sousa's user avatar

2

For SDK ver 21 and above

android:indeterminateTint="@color/orange"

in XML Works for me, is easy enough.

answered Apr 21, 2017 at 12:38

Mughil's user avatar

MughilMughil

6856 silver badges8 bronze badges

1

Trust me, the easiest solution is just paste this inside progressBar :

android:indeterminateTint="@android:color/white"

answered Nov 8, 2021 at 15:42

A.I.Shakil's user avatar

A.I.ShakilA.I.Shakil

7354 silver badges18 bronze badges

THis is what i did. Worked.

ProgressBar:

<ProgressBar
            android:id="@+id/progressBar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="4"
            android:indeterminateDrawable="@drawable/progressdrawable"
           />

progressdrawable.xml:
Here use gradient to change colour as you like. And android:toDegrees=»X» increse the value of X and progressbar rotate fast. Decrease and it rotate slow.Customize according to your needs.

<?xml version="1.0" encoding="utf-8"?>
     <rotate xmlns:android="http://schemas.android.com/apk/res/android"
            android:duration="4000"
            android:fromDegrees="0"
            android:pivotX="50%"
            android:pivotY="50%"
            android:toDegrees="360" >

            <shape
                android:innerRadius="20dp"
                android:shape="ring"
                android:thickness="4dp"
                android:useLevel="false" >
                <size
                    android:height="48dp"
                    android:width="48dp" />

                <gradient
                    android:centerColor="#80ec7e2a"
                    android:centerY="0.5"
                    android:endColor="#ffec7e2a"
                    android:startColor="#00ec7e2a"
                    android:type="sweep"
                    android:useLevel="false" />
            </shape>

        </rotate>

sample:
enter image description here

answered Jan 31, 2018 at 6:44

Debasish Ghosh's user avatar

1

Add in ProgressBar inside of Xml

For SDK ver 21 and above

android:indeterminateTint="@color/red"

answered Jun 23, 2021 at 3:04

Mark Nashat's user avatar

Mark NashatMark Nashat

5907 silver badges8 bronze badges

2

Hit the same problem while working on modifying the look/feel of the default progress bar. Here is some more info that will hopefully help people :)

  • The name of the xml file must only contain characters: a-z0-9_. (ie. no capitals!)
  • To reference your «drawable» it is R.drawable.filename
  • To override the default look, you use myProgressBar.setProgressDrawable(...), however you need can’t just refer to your custom layout as R.drawable.filename, you need to retrieve it as a Drawable:
    Resources res = getResources();
    myProgressBar.setProgressDrawable(res.getDrawable(R.drawable.filename);
    
  • You need to set style before setting progress/secondary progress/max (setting it afterwards for me resulted in an ’empty’ progress bar)

answered Feb 28, 2011 at 12:41

pyko's user avatar

pykopyko

3,3595 gold badges25 silver badges31 bronze badges

You can try to change your Styles, Themes, or using android:indeterminateTint=»@color/yourColor» anywhere you want, but there’s just one way o doing that will work on any Android SKD version:

If you progress bar is not indeterminate, please use:

progressBar.getProgressDrawable().setColorFilter(ContextCompat.getColor(context, R.color.yourColor), PorterDuff.Mode.SRC_IN );

If you progress bar is indeterminate, please use:

progressBar.getIndeterminateDrawable().setColorFilter(ContextCompat.getColor(getContext(), R.color.yourColor), PorterDuff.Mode.SRC_IN );

It’s sad that Android is such a mess!

answered Dec 4, 2017 at 16:53

Adriano Moutinho's user avatar

1

How I did it in horizontal ProgressBar:

    LayerDrawable layerDrawable = (LayerDrawable) progressBar.getProgressDrawable();
    Drawable progressDrawable = layerDrawable.findDrawableByLayerId(android.R.id.progress);
    progressDrawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);

answered Dec 16, 2015 at 11:36

mieszk3's user avatar

mieszk3mieszk3

2663 silver badges9 bronze badges

2

There’s probably one thing that hasn’t been referred to in this answer:

If your theme is inheriting from Theme.AppCompat, ProgressBar will assume the color you defined as "colorAccent" in your theme.

So, using..

<item name="colorAccent">@color/custom_color</item>

..will tint the color of the ProgressBar automagically to the @color/custom_color .

answered Jan 21, 2016 at 18:53

Henrique de Sousa's user avatar

1

Simplest Solution if you want to change the colour in the layout xml file, use the below code and use indeterminateTint property for your desired color.

    <ProgressBar
      android:id="@+id/progressBar"
      style="?android:attr/progressBarStyle"
      android:layout_width="wrap_content"
      android:indeterminate="true"
      android:indeterminateTintMode="src_atop"
      android:indeterminateTint="#ddbd4e"
      android:layout_height="wrap_content"
      android:layout_marginBottom="20dp"
      android:layout_alignParentBottom="true"
      android:layout_centerHorizontal="true" />

answered Nov 25, 2017 at 4:27

Naveed Ahmad's user avatar

Naveed AhmadNaveed Ahmad

6,5672 gold badges58 silver badges83 bronze badges

0

The most simple way of changing the foreground and background colour of a progress bar is

<ProgressBar
                        style="@android:style/Widget.ProgressBar.Horizontal"
                        android:id="@+id/pb_main"
                        android:layout_width="match_parent"
                        android:layout_height="8dp"
                        android:progress="30"
                        android:progressTint="#82e9de"
                        android:progressBackgroundTint="#82e9de"
                        />

just add

                        android:progressTint="#82e9de" //for foreground colour
                        android:progressBackgroundTint="#82e9de" //for background colour

answered Apr 18, 2020 at 6:50

Satyam Patil's user avatar

1

This solution worked for me :

<style name="Progressbar.White" parent="AppTheme">
    <item name="colorControlActivated">@color/white</item>
</style>

<ProgressBar
    android:layout_width="@dimen/d_40"
    android:layout_height="@dimen/d_40"
    android:indeterminate="true"
    android:theme="@style/Progressbar.White"/>

Hiroyuki Nuri's user avatar

Hiroyuki Nuri

5,21815 gold badges71 silver badges124 bronze badges

answered Aug 1, 2017 at 13:55

S.Javed's user avatar

S.JavedS.Javed

3303 silver badges7 bronze badges

0

For default ( indeterminate )

add

android:indeterminateTint="@color/white"

for determinate

    android:progressTint="@color/color_1"

    //OR
    progressBar.getProgressDrawable().setColorFilter( PorterDuffColorFilter(Color.RED,android.graphics.PorterDuff.Mode.SRC_IN));

answered Oct 7, 2021 at 9:19

Nasib's user avatar

NasibNasib

1,0181 gold badge11 silver badges22 bronze badges

To change horizontal ProgressBar color (in kotlin):

fun tintHorizontalProgress(progress: ProgressBar, @ColorInt color: Int = ContextCompat.getColor(progress.context, R.color.colorPrimary)){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        progress.progressTintList = ColorStateList.valueOf(color)
    } else{
        val layerDrawable = progress.progressDrawable as? LayerDrawable
        val progressDrawable = layerDrawable?.findDrawableByLayerId(android.R.id.progress)
        progressDrawable?.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
    }
}

To change indeterminate ProgressBar color:

fun tintIndeterminateProgress(progress: ProgressBar, @ColorInt color: Int = ContextCompat.getColor(progress.context, R.color.colorPrimary)){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        progress.indeterminateTintList = ColorStateList.valueOf(color)
    } else {
        (progress.indeterminateDrawable as? LayerDrawable)?.apply {
            if (numberOfLayers >= 2) {
                setId(0, android.R.id.progress)
                setId(1, android.R.id.secondaryProgress)
                val progressDrawable = findDrawableByLayerId(android.R.id.progress).mutate()
                progressDrawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
            }
        }
    }
}

And it finally normally tint pre-lollipop progressBars

tinted progress on api 19

Community's user avatar

answered Apr 5, 2019 at 14:19

John's user avatar

JohnJohn

1,38014 silver badges15 bronze badges

0

One more little thing, the theme solution does work if you inherit a base theme, so for app compact your theme should be:

<style name="AppTheme.Custom" parent="@style/Theme.AppCompat">
    <item name="colorAccent">@color/custom</item>
</style>

And then set this in the progress bar theme

<ProgressBar
    android:id="@+id/progressCircle_progressBar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:theme="@style/AppTheme.Custom"
    android:indeterminate="true"/>

answered May 23, 2017 at 19:27

Calin's user avatar

CalinCalin

6,5815 gold badges47 silver badges79 bronze badges

0

Simply use:

DrawableCompat.setTint(progressBar.getIndeterminateDrawable(),yourColor)

answered May 3, 2020 at 14:15

Amir Hossein Ghasemi's user avatar

1

simply use:

PorterDuff.Mode mode = PorterDuff.Mode.SRC_IN;
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
    mode = PorterDuff.Mode.MULTIPLY;
}

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    progressBar.setProgressTintList(ColorStateList.valueOf(Color.RED));
    progressBar.setProgressBackgroundTintList(ColorStateList.valueOf(Color.RED));
} else {
    Drawable progressDrawable;
    progressDrawable = (progressBar.isIndeterminate() ? progressBar.getIndeterminateDrawable() : progressBar.getProgressDrawable()).mutate();
    progressDrawable.setColorFilter(context.getResources().getColor(Color.RED), mode);
    progressBar.setProgressDrawable(progressDrawable);
}

answered Aug 10, 2019 at 15:57

Mohammad Fneish's user avatar

Mohammad FneishMohammad Fneish

7391 gold badge8 silver badges19 bronze badges

Horizontal progress bar custom material style :

To change color of background and progress of horizontal progress bar.

<style name="MyProgressBar" parent="@style/Widget.AppCompat.ProgressBar.Horizontal">
    <item name="android:progressBackgroundTint">#69f0ae</item>
    <item name="android:progressTint">#b71c1c</item>
    <item name="android:minWidth">200dp</item>
</style>

Apply it to progress bar by setting style attribute, for custom material styles and custom progress bar check http://www.zoftino.com/android-progressbar-and-custom-progressbar-examples

answered Sep 21, 2017 at 14:53

Arnav Rao's user avatar

Arnav RaoArnav Rao

6,5122 gold badges32 silver badges31 bronze badges

1

Use the android.support.v4.graphics.drawable.DrawableCompat:

            Drawable progressDrawable = progressBar.getIndeterminateDrawable();
            if (progressDrawable  != null) {
                Drawable mutateDrawable = progressDrawable.mutate();
                DrawableCompat.setTint(mutateDrawable, primaryColor);
                progressBar.setProgressDrawable(mutateDrawable);
            }

answered Mar 15, 2018 at 13:35

Alécio Carvalho's user avatar

Alécio CarvalhoAlécio Carvalho

13.3k5 gold badges67 silver badges73 bronze badges

Asked
13 years, 1 month ago

Viewed
754k times

I’m using an horizontal progress bar in my Android application, and I want to change its progress color (which is Yellow by default). How can I do it using code (not XML)?

Mahozad's user avatar

Mahozad

15.3k11 gold badges101 silver badges119 bronze badges

asked Jan 7, 2010 at 14:13

WhiteTigerK's user avatar

4

For a horizontal ProgressBar, you can use a ColorFilter, too, like this:

progressBar.getProgressDrawable().setColorFilter(
    Color.RED, android.graphics.PorterDuff.Mode.SRC_IN);

Red ProgressBar using color filter

Note: This modifies the appearance of all progress bars in your app. To only modify one specific progress bar, do this:

Drawable progressDrawable = progressBar.getProgressDrawable().mutate();
progressDrawable.setColorFilter(Color.RED, android.graphics.PorterDuff.Mode.SRC_IN);
progressBar.setProgressDrawable(progressDrawable);

If progressBar is indeterminate then use getIndeterminateDrawable() instead of getProgressDrawable().

Since Lollipop (API 21) you can set a progress tint:

progressBar.setProgressTintList(ColorStateList.valueOf(Color.RED));

Red ProgressBar using progress tint

answered Apr 4, 2013 at 11:25

Torben Kohlmeier's user avatar

Torben KohlmeierTorben Kohlmeier

6,6231 gold badge15 silver badges15 bronze badges

16

This is not programmatically but I think it could help a lot of people anyway.
I tried a lot and the most efficient way was to add this lines to my ProgressBar in the .xml File:

            android:indeterminate="true"
            android:indeterminateTintMode="src_atop"
            android:indeterminateTint="@color/secondary"

So in the end this code did it for me:

<ProgressBar
            android:id="@+id/progressBar"
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:layout_marginTop="50dp"
            android:layout_marginBottom="50dp"
            android:visibility="visible"
            android:indeterminate="true"
            android:indeterminateTintMode="src_atop"
            android:indeterminateTint="@color/secondary">

This solution works for API 21+

Vadim Kotov's user avatar

Vadim Kotov

7,9648 gold badges48 silver badges62 bronze badges

answered Jul 11, 2015 at 16:04

FFirmenich's user avatar

FFirmenichFFirmenich

5,4511 gold badge17 silver badges28 bronze badges

6

I’m sorry that it’s not the answer, but what’s driving the requirement setting it from code ?
And .setProgressDrawable should work if it’s defined correctly

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

<item android:id="@android:id/background">
    <shape>
        <corners android:radius="5dip" />
        <gradient
                android:startColor="#ff9d9e9d"
                android:centerColor="#ff5a5d5a"
                android:centerY="0.75"
                android:endColor="#ff747674"
                android:angle="270"
        />
    </shape>
</item>

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

<item android:id="@android:id/progress">
    <clip>
        <shape>
            <corners
                android:radius="5dip" />
            <gradient
                android:startColor="@color/progress_start"
                android:endColor="@color/progress_end"
                android:angle="270" 
            />
        </shape>
    </clip>
</item>

</layer-list>

WarrenFaith's user avatar

WarrenFaith

57.3k25 gold badges134 silver badges148 bronze badges

answered Jan 7, 2010 at 15:00

Alex Volovoy's user avatar

Alex VolovoyAlex Volovoy

67.5k13 gold badges73 silver badges54 bronze badges

11

For my indeterminate progressbar (spinner) I just set a color filter on the drawable. Works great and just one line.

Example where setting color to red:

ProgressBar spinner = new android.widget.ProgressBar(
                context,
                null,
                android.R.attr.progressBarStyle);

spinner.getIndeterminateDrawable().setColorFilter(0xFFFF0000, android.graphics.PorterDuff.Mode.MULTIPLY);

enter image description here

answered Jun 7, 2012 at 9:14

jhavatar's user avatar

jhavatarjhavatar

3,2061 gold badge17 silver badges11 bronze badges

5

This is an old question, but using theme is not mentioned here. If your default theme is using AppCompat, your ProgressBar‘s color will be colorAccent you have defined.

Changing colorAccent will also change your ProgressBar‘s color, but there changes also reflects at multiple places. So, if you want a different color just for a specific PregressBar you can do that by applying theme to that ProgressBar :

  • Extend your default theme and override colorAccent

    <style name="AppTheme.WhiteAccent">
        <item name="colorAccent">@color/white</item> <!-- Whatever color you want-->
    </style>
    
  • And in ProgressBar add the android:theme attribute:

    android:theme="@style/AppTheme.WhiteAccent"
    

So it will look something like this:

<ProgressBar
        android:id="@+id/loading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:padding="10dp"
        android:theme="@style/AppTheme.WhiteAccent" />

So you are just changing a colorAccent for your particular ProgressBar.

Note: Using style will not work. You need to use android:theme only.
You can find more use of theme here: https://plus.google.com/u/0/+AndroidDevelopers/posts/JXHKyhsWHAH

answered Jul 9, 2016 at 13:08

kirtan403's user avatar

kirtan403kirtan403

7,1476 gold badges52 silver badges95 bronze badges

9

All API

if use all API just create the theme in style

style.xml

<resources>

    //...

    <style name="progressBarBlue" parent="@style/Theme.AppCompat">
        <item name="colorAccent">@color/blue</item>
    </style>

</resources>

and use in progress

<ProgressBar
    ...
    android:theme="@style/progressBarBlue" />

API level 21 and higher

if used in API level 21 and higher just use this code:

<ProgressBar
   //...
   android:indeterminate="true"
   android:indeterminateTintMode="src_atop"
   android:indeterminateTint="@color/secondary"/>

answered Sep 24, 2018 at 14:03

Rasoul Miri's user avatar

Rasoul MiriRasoul Miri

10.2k1 gold badge64 silver badges75 bronze badges

1

This works for me. It also works for lower version too. Add this to your syles.xml

<style name="ProgressBarTheme" parent="ThemeOverlay.AppCompat.Light">
<item name="colorAccent">@color/colorPrimary</item>
</style>

And use it like this in xml

<ProgressBar
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:theme="@style/ProgressBarTheme"
   />

answered Sep 25, 2019 at 5:39

Devinder Jhinjer's user avatar

3

This worked for me :

<ProgressBar
 android:indeterminateTint="#d60909"
 ... />

answered Jul 6, 2017 at 5:40

MOH3N's user avatar

MOH3NMOH3N

8859 silver badges14 bronze badges

1

as per some of the suggestions, you CAN specify a shape and clipdrawable with a colour, then set it. I have this working programatically. This is how I do it..

First make sure you import the drawable library..

import android.graphics.drawable.*;

Then use the code similar to below;

ProgressBar pg = (ProgressBar)row.findViewById(R.id.progress);
final float[] roundedCorners = new float[] { 5, 5, 5, 5, 5, 5, 5, 5 };
pgDrawable = new ShapeDrawable(new RoundRectShape(roundedCorners, null,null));
String MyColor = "#FF00FF";
pgDrawable.getPaint().setColor(Color.parseColor(MyColor));
ClipDrawable progress = new ClipDrawable(pgDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL);
pg.setProgressDrawable(progress);   
pg.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.progress_horizontal));
pg.setProgress(45);

answered Mar 6, 2011 at 9:46

PaulieG's user avatar

PaulieGPaulieG

3413 silver badges2 bronze badges

6

if Indeterminate:

((ProgressBar)findViewById(R.id.progressBar))
    .getIndeterminateDrawable()
    .setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);

Paweł Tomkiel's user avatar

answered Mar 22, 2015 at 17:24

the.knife's user avatar

the.knifethe.knife

4094 silver badges3 bronze badges

1

android:progressTint="#ffffff" 

answered Sep 14, 2016 at 13:32

Paul's user avatar

PaulPaul

7741 gold badge9 silver badges15 bronze badges

0

Nowadays in 2016 I found some pre-Lollipop devices don’t honour the colorAccent setting, so my final solution for all APIs is now the following:

// fixes pre-Lollipop progressBar indeterminateDrawable tinting
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {

    Drawable wrapDrawable = DrawableCompat.wrap(mProgressBar.getIndeterminateDrawable());
    DrawableCompat.setTint(wrapDrawable, ContextCompat.getColor(getContext(), android.R.color.holo_green_light));
    mProgressBar.setIndeterminateDrawable(DrawableCompat.unwrap(wrapDrawable));
} else {
    mProgressBar.getIndeterminateDrawable().setColorFilter(ContextCompat.getColor(getContext(), android.R.color.holo_green_light), PorterDuff.Mode.SRC_IN);
}

For bonus points, it doesn’t use any deprecated code. Try it!

answered Sep 14, 2016 at 10:31

Henrique de Sousa's user avatar

2

For SDK ver 21 and above

android:indeterminateTint="@color/orange"

in XML Works for me, is easy enough.

answered Apr 21, 2017 at 12:38

Mughil's user avatar

MughilMughil

6856 silver badges8 bronze badges

1

Trust me, the easiest solution is just paste this inside progressBar :

android:indeterminateTint="@android:color/white"

answered Nov 8, 2021 at 15:42

A.I.Shakil's user avatar

A.I.ShakilA.I.Shakil

7354 silver badges18 bronze badges

THis is what i did. Worked.

ProgressBar:

<ProgressBar
            android:id="@+id/progressBar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="4"
            android:indeterminateDrawable="@drawable/progressdrawable"
           />

progressdrawable.xml:
Here use gradient to change colour as you like. And android:toDegrees=»X» increse the value of X and progressbar rotate fast. Decrease and it rotate slow.Customize according to your needs.

<?xml version="1.0" encoding="utf-8"?>
     <rotate xmlns:android="http://schemas.android.com/apk/res/android"
            android:duration="4000"
            android:fromDegrees="0"
            android:pivotX="50%"
            android:pivotY="50%"
            android:toDegrees="360" >

            <shape
                android:innerRadius="20dp"
                android:shape="ring"
                android:thickness="4dp"
                android:useLevel="false" >
                <size
                    android:height="48dp"
                    android:width="48dp" />

                <gradient
                    android:centerColor="#80ec7e2a"
                    android:centerY="0.5"
                    android:endColor="#ffec7e2a"
                    android:startColor="#00ec7e2a"
                    android:type="sweep"
                    android:useLevel="false" />
            </shape>

        </rotate>

sample:
enter image description here

answered Jan 31, 2018 at 6:44

Debasish Ghosh's user avatar

1

Add in ProgressBar inside of Xml

For SDK ver 21 and above

android:indeterminateTint="@color/red"

answered Jun 23, 2021 at 3:04

Mark Nashat's user avatar

Mark NashatMark Nashat

5907 silver badges8 bronze badges

2

Hit the same problem while working on modifying the look/feel of the default progress bar. Here is some more info that will hopefully help people :)

  • The name of the xml file must only contain characters: a-z0-9_. (ie. no capitals!)
  • To reference your «drawable» it is R.drawable.filename
  • To override the default look, you use myProgressBar.setProgressDrawable(...), however you need can’t just refer to your custom layout as R.drawable.filename, you need to retrieve it as a Drawable:
    Resources res = getResources();
    myProgressBar.setProgressDrawable(res.getDrawable(R.drawable.filename);
    
  • You need to set style before setting progress/secondary progress/max (setting it afterwards for me resulted in an ’empty’ progress bar)

answered Feb 28, 2011 at 12:41

pyko's user avatar

pykopyko

3,3595 gold badges25 silver badges31 bronze badges

You can try to change your Styles, Themes, or using android:indeterminateTint=»@color/yourColor» anywhere you want, but there’s just one way o doing that will work on any Android SKD version:

If you progress bar is not indeterminate, please use:

progressBar.getProgressDrawable().setColorFilter(ContextCompat.getColor(context, R.color.yourColor), PorterDuff.Mode.SRC_IN );

If you progress bar is indeterminate, please use:

progressBar.getIndeterminateDrawable().setColorFilter(ContextCompat.getColor(getContext(), R.color.yourColor), PorterDuff.Mode.SRC_IN );

It’s sad that Android is such a mess!

answered Dec 4, 2017 at 16:53

Adriano Moutinho's user avatar

1

How I did it in horizontal ProgressBar:

    LayerDrawable layerDrawable = (LayerDrawable) progressBar.getProgressDrawable();
    Drawable progressDrawable = layerDrawable.findDrawableByLayerId(android.R.id.progress);
    progressDrawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);

answered Dec 16, 2015 at 11:36

mieszk3's user avatar

mieszk3mieszk3

2663 silver badges9 bronze badges

2

There’s probably one thing that hasn’t been referred to in this answer:

If your theme is inheriting from Theme.AppCompat, ProgressBar will assume the color you defined as "colorAccent" in your theme.

So, using..

<item name="colorAccent">@color/custom_color</item>

..will tint the color of the ProgressBar automagically to the @color/custom_color .

answered Jan 21, 2016 at 18:53

Henrique de Sousa's user avatar

1

Simplest Solution if you want to change the colour in the layout xml file, use the below code and use indeterminateTint property for your desired color.

    <ProgressBar
      android:id="@+id/progressBar"
      style="?android:attr/progressBarStyle"
      android:layout_width="wrap_content"
      android:indeterminate="true"
      android:indeterminateTintMode="src_atop"
      android:indeterminateTint="#ddbd4e"
      android:layout_height="wrap_content"
      android:layout_marginBottom="20dp"
      android:layout_alignParentBottom="true"
      android:layout_centerHorizontal="true" />

answered Nov 25, 2017 at 4:27

Naveed Ahmad's user avatar

Naveed AhmadNaveed Ahmad

6,5672 gold badges58 silver badges83 bronze badges

0

The most simple way of changing the foreground and background colour of a progress bar is

<ProgressBar
                        style="@android:style/Widget.ProgressBar.Horizontal"
                        android:id="@+id/pb_main"
                        android:layout_width="match_parent"
                        android:layout_height="8dp"
                        android:progress="30"
                        android:progressTint="#82e9de"
                        android:progressBackgroundTint="#82e9de"
                        />

just add

                        android:progressTint="#82e9de" //for foreground colour
                        android:progressBackgroundTint="#82e9de" //for background colour

answered Apr 18, 2020 at 6:50

Satyam Patil's user avatar

1

This solution worked for me :

<style name="Progressbar.White" parent="AppTheme">
    <item name="colorControlActivated">@color/white</item>
</style>

<ProgressBar
    android:layout_width="@dimen/d_40"
    android:layout_height="@dimen/d_40"
    android:indeterminate="true"
    android:theme="@style/Progressbar.White"/>

Hiroyuki Nuri's user avatar

Hiroyuki Nuri

5,21815 gold badges71 silver badges124 bronze badges

answered Aug 1, 2017 at 13:55

S.Javed's user avatar

S.JavedS.Javed

3303 silver badges7 bronze badges

0

For default ( indeterminate )

add

android:indeterminateTint="@color/white"

for determinate

    android:progressTint="@color/color_1"

    //OR
    progressBar.getProgressDrawable().setColorFilter( PorterDuffColorFilter(Color.RED,android.graphics.PorterDuff.Mode.SRC_IN));

answered Oct 7, 2021 at 9:19

Nasib's user avatar

NasibNasib

1,0181 gold badge11 silver badges22 bronze badges

To change horizontal ProgressBar color (in kotlin):

fun tintHorizontalProgress(progress: ProgressBar, @ColorInt color: Int = ContextCompat.getColor(progress.context, R.color.colorPrimary)){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        progress.progressTintList = ColorStateList.valueOf(color)
    } else{
        val layerDrawable = progress.progressDrawable as? LayerDrawable
        val progressDrawable = layerDrawable?.findDrawableByLayerId(android.R.id.progress)
        progressDrawable?.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
    }
}

To change indeterminate ProgressBar color:

fun tintIndeterminateProgress(progress: ProgressBar, @ColorInt color: Int = ContextCompat.getColor(progress.context, R.color.colorPrimary)){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        progress.indeterminateTintList = ColorStateList.valueOf(color)
    } else {
        (progress.indeterminateDrawable as? LayerDrawable)?.apply {
            if (numberOfLayers >= 2) {
                setId(0, android.R.id.progress)
                setId(1, android.R.id.secondaryProgress)
                val progressDrawable = findDrawableByLayerId(android.R.id.progress).mutate()
                progressDrawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
            }
        }
    }
}

And it finally normally tint pre-lollipop progressBars

tinted progress on api 19

Community's user avatar

answered Apr 5, 2019 at 14:19

John's user avatar

JohnJohn

1,38014 silver badges15 bronze badges

0

One more little thing, the theme solution does work if you inherit a base theme, so for app compact your theme should be:

<style name="AppTheme.Custom" parent="@style/Theme.AppCompat">
    <item name="colorAccent">@color/custom</item>
</style>

And then set this in the progress bar theme

<ProgressBar
    android:id="@+id/progressCircle_progressBar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:theme="@style/AppTheme.Custom"
    android:indeterminate="true"/>

answered May 23, 2017 at 19:27

Calin's user avatar

CalinCalin

6,5815 gold badges47 silver badges79 bronze badges

0

Simply use:

DrawableCompat.setTint(progressBar.getIndeterminateDrawable(),yourColor)

answered May 3, 2020 at 14:15

Amir Hossein Ghasemi's user avatar

1

simply use:

PorterDuff.Mode mode = PorterDuff.Mode.SRC_IN;
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
    mode = PorterDuff.Mode.MULTIPLY;
}

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    progressBar.setProgressTintList(ColorStateList.valueOf(Color.RED));
    progressBar.setProgressBackgroundTintList(ColorStateList.valueOf(Color.RED));
} else {
    Drawable progressDrawable;
    progressDrawable = (progressBar.isIndeterminate() ? progressBar.getIndeterminateDrawable() : progressBar.getProgressDrawable()).mutate();
    progressDrawable.setColorFilter(context.getResources().getColor(Color.RED), mode);
    progressBar.setProgressDrawable(progressDrawable);
}

answered Aug 10, 2019 at 15:57

Mohammad Fneish's user avatar

Mohammad FneishMohammad Fneish

7391 gold badge8 silver badges19 bronze badges

Horizontal progress bar custom material style :

To change color of background and progress of horizontal progress bar.

<style name="MyProgressBar" parent="@style/Widget.AppCompat.ProgressBar.Horizontal">
    <item name="android:progressBackgroundTint">#69f0ae</item>
    <item name="android:progressTint">#b71c1c</item>
    <item name="android:minWidth">200dp</item>
</style>

Apply it to progress bar by setting style attribute, for custom material styles and custom progress bar check http://www.zoftino.com/android-progressbar-and-custom-progressbar-examples

answered Sep 21, 2017 at 14:53

Arnav Rao's user avatar

Arnav RaoArnav Rao

6,5122 gold badges32 silver badges31 bronze badges

1

Use the android.support.v4.graphics.drawable.DrawableCompat:

            Drawable progressDrawable = progressBar.getIndeterminateDrawable();
            if (progressDrawable  != null) {
                Drawable mutateDrawable = progressDrawable.mutate();
                DrawableCompat.setTint(mutateDrawable, primaryColor);
                progressBar.setProgressDrawable(mutateDrawable);
            }

answered Mar 15, 2018 at 13:35

Alécio Carvalho's user avatar

Alécio CarvalhoAlécio Carvalho

13.3k5 gold badges67 silver badges73 bronze badges

Тег <progress> является индикатором хода выполнения задачи. Например, загрузки файла
или процента проголосовавших к определенному времени.

Атрибуты тега <progress>

value
Текущее значение.
max
Максимальное значение (по умолчанию 1).

Должно выполняться неравенство:

  • 0 ≤ value ≤ max

Числовое значение value можно менять с помощью JavaScript.

Для тега <progress> также доступны общие атрибуты и атрибуты обработки событий.

Внешний вид элемента <progress> зависит от операционной системы и браузера.

<style type="text/css">
    .default-progressbar progress {
        margin-top: 10px;
        height: 25px;
        width: 100%;
    }
</style>
<div class="default-progressbar">
    <progress value="0">Выполнено 0% работы</progress>
    <progress value="0.75">Выполнено 75% работы</progress>
</div>

Браузеры, не отображающие тег <progress> выводят текст из контейнера <progress>…</progress>.

РЕЗУЛЬТАТ:

Выполнено 0% работы
Выполнено 75% работы

CSS-стили элемента <progress> можно изменять. Для этого сначала надо отменить стили браузеров по умолчанию.

progress {
/* Отключаем стиль (как правило, не требуется, но на всякий случай)  */
appearance: none;
-moz-appearance: none;
-webkit-appearance: none;
/* Убираем границы по умолчанию в Firefox и Opera */
border: none;
/* Чтобы фоновое изображение в Safari работало, как надо */
background-size: auto;
}
Изменение цвета фона элемента <progress>
/* Firefox  */
progress {
background: #fac;
}
/* Chrome */
progress::-webkit-progress-bar {
background: #fac;
}

Несмотря на то, что правила одинаковые, объединять их в одно нельзя – работать не будет!

Изменение цвета значения элемента <progress>

Opera 11 и 12 не допускает изменение цвета индикатора – он остается зеленым.

/* IE10 */
progress {
color: #e0a;
}
/* Firefox */
progress::-moz-progress-bar {
background: #e0a;
}
/* Chrome */
progress::-webkit-progress-value {
background: #e0a;
}

РЕЗУЛЬТАТ:

Выполнено 25% работы

Градиент в качестве значения <progress>

Для Internet Explorer цвет значения <progress> задается свойством color, т.е. никакого градиента для IE не получится :(

<style type="text/css">
    .gradient-progressbar progress {
        appearance: none;
        -moz-appearance: none;
        -webkit-appearance: none;
        border: none;
        margin-top: 10px;
        background: #eee;
        border: 0;
        width: 100%;
        height: 25px;
        border-radius: 9px;
        color: #9c3;
    }
    .gradient-progressbar progress::-webkit-progress-bar {
        background: #eeeeee;
        border-radius: 9px;
    }
    .gradient-progressbar progress::-webkit-progress-value {
        background: linear-gradient(to bottom, #cf9 0%, #9c3 100%);
        border-radius: 9px;
    }
    .gradient-progressbar progress::-moz-progress-bar {
        background: linear-gradient(to bottom, #cf9 0%, #9c3 100%);
        border-radius: 9px;
    }
</style>
<div class="gradient-progressbar">
    <progress value="0.5">Выполнено 50% работы</progress>
</div>

РЕЗУЛЬТАТ:

Выполнено 50% работы

Вопрос «Как поменять цвет полоски у ProgressBar» достаточно частый для языка C#. На самом деле не знаю почему разработчики .NET не добавили свойство изменения цвета полоски на другой — а ведь штука то на самом деле нужная. Так же не плохой была бы возможность отображения текущего прогресса в процентах или относительно какого либо числа, например 5 из 1000. Сегодня я решил поделиться с Вами набросками прогресса который может менять цвет полоски и отображать текущий прогресс в виде текста в двух вариантах: проценты и текущее значение относительно максимального значения.

К сожалению то, о чем я сейчас Вам говорю нельзя реализовать с помощью стандартного контрола ProgressBar. Поэтому если Вы хотите поменять цвет полоски, то Вам нужно будет писать свой прогресс бар. Я не буду вдаваться в подробности о том как создавать свой собственный control. Об это я уже говорил в данном посте. Так же я не буду наводить красоту в нашем разрабатываемом контроле, а остановлюсь лишь на минимальном функционале. Если Вы захотите как-то украсить наш control, то без проблем сможете это сделать, например добавив градиенты и т.п.

Сейчас я приведу листинг нашего ProgressBar который может менять цвет полоски, а затем опишу как им пользоваться:

using System;
using System.Drawing;
using System.Windows.Forms;

namespace FsLib
{
    class FsProgressBar: Control
    {
        public enum FsProgressTextType
        {
            AsIs, Percent
        }

        //Cal when Value was changed
        public event EventHandler ValueChanged;
        //Call when Value == MaxValue
        public event EventHandler ValuesIsMaximum;

        private Int32 minValue;
        public Int32 MinValue 
        {
            get 
            {
                return this.minValue;
            }
            set
            {
                if (value >= this.MaxValue)
                {
                    throw new Exception("MinValue must be less than MaxValue");
                }
                this.minValue = value;
                this.Invalidate();
            }
        }
        
        private Int32 maxValue;
        public Int32 MaxValue 
        {
            get
            {
                return this.maxValue;
            }
            set
            {
                if (value <= this.MinValue)
                {
                    throw new Exception("MaxValue must be more than MinValue");
                }
                this.maxValue = value;
                this.Invalidate();
            }
        }

        private Int32 value;
        public Int32 Value
        {
            get
            {
                return this.value;
            }
            set
            {
                if (value < this.MinValue || value > this.maxValue)
                {
                    throw new Exception("Value must be between MinValue and MaxValue");
                }
                this.value = value;
                if (this.value == this.MaxValue && this.ValuesIsMaximum != null)
                {
                    this.ValuesIsMaximum(this, new EventArgs());
                }
                if (this.ValueChanged != null)
                {
                    this.ValueChanged(this, new EventArgs());
                }
                this.Invalidate();
            }
        }

        private Int32 borderWidth;
        public Int32 BorderWidth
        {
            get
            {
                return this.borderWidth;
            }
            set
            {
                if (value < 0)
                {
                    throw new Exception("Border width can not be negative");
                }
                this.borderWidth = value;
            }
        }
        
        public System.Drawing.Color BorderColor { get; set; }
        public System.Drawing.Color ProgressColor { get; set; }
        public Boolean ShowProgressText { get; set; }
        public FsProgressTextType ProgressTextType { get; set; }

        public FsProgressBar()
        {
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            this.minValue = 0;
            this.maxValue = 100;
            this.value = 0;
            this.BorderWidth = 0;
            this.BorderColor = Color.Black;
            this.BackColor = SystemColors.Control;
            this.ForeColor = Color.Black;
            this.ProgressColor = Color.Yellow;
            this.ShowProgressText = true;
            this.Paint += new PaintEventHandler(FsProgressBar_Paint);
            this.Size = new Size(200, 30);
            this.ProgressTextType = FsProgressTextType.AsIs;
        }

        protected void FsProgressBar_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.FillRectangle(new SolidBrush(this.BackColor), new Rectangle(0, 0, this.Width, this.Height));
            e.Graphics.FillRectangle(new SolidBrush(this.ProgressColor), new Rectangle(0, 0, (this.Value * this.Width) / this.MaxValue, this.Height));
            if (this.BorderWidth > 0)
            {
                e.Graphics.DrawRectangle(new Pen(this.BorderColor, this.BorderWidth), this.DisplayRectangle);
            }
            if (this.ShowProgressText)
            {
                string text = String.Empty;
                switch (this.ProgressTextType)
                {
                    case FsProgressTextType.AsIs:
                        text = this.Value + " / " + this.MaxValue;
                        break;
                    case FsProgressTextType.Percent:
                        text = ((this.Value * 100) / this.MaxValue).ToString() + "%";
                        break;
                }
                System.Drawing.SizeF size = e.Graphics.MeasureString(text, this.Font);
                e.Graphics.DrawString(text, this.Font, new SolidBrush(this.ForeColor), new PointF(this.Width / 2 - size.Width / 2, this.Height / 2 - size.Height / 2)); 
            }
        }
    }
}

Чтобы создать данный контрол Вам нужно написать следующий код:

FsLib.FsProgressBar fsProgress = new FsLib.FsProgressBar();

Рассмотрим основные свойства нашего объекта:
fsProgress.ForeColor — Цвет отображаемого текста;
fsProgress.Font — Стиль отображаемого текста;
fsProgress.ProgressTextType — Как отображать текст прогресса (проценты или текущее значение);
fsProgress.ShowProgressText — Нужно ли отображать текст прогресса;
fsProgress.BackColor — Цвет фона;
fsProgress.ProgressColor — Цвет полоски прогресса;
fsProgress.BorderColor — Цвет рамки;
fsProgress.BorderWidth — Ширина рамки;
fsProgress.MinValue — Минимальное значение;
fsProgress.MaxValue — Максимальное значение;
fsProgress.Value — Текущее значение прогресса;

Рассмотрим основные события:
fsProgress.ValuesChanged — Вызывается при изменении значения;
fsProgress.ValuesIsMaximum — Вызывается если значение прогресса достигло максимума;

Запись опубликована в рубрике C# с метками C#, Control, custom, example, ProgessBar, progress bar, бар, изменить, Контрол, отобрзаить текст, Пример, прогресс, свой progress bar, цвет. Добавьте в закладки постоянную ссылку.

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    In this article, we will see how we can add color to a ProgressBar in android. Android ProgressBar is a user interface control that indicates the progress of an operation. For example, downloading a file, uploading a file on the internet we can see the ProgressBar estimate the time remaining in operation. Note in this article we will be using Java and XML to set the color.

    Step by Step Implementation

    Step 1: Create a New Project

    • To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. 
    • Note that select Java as the programming language.

    Step 2: Create a custom ProgressBar

    • Go to the app > res > drawable > right-click > New > Drawable Resource File and name the file as progress_bg.
    • Inside the XML file add a rotate tag with some attributes(see code)
    • Inside rotate tag create a shape tag within which create the size and gradient tag
    • Attributes of these tags are given in the code below. 
    • Below is the code for the progress_bg.xml file. 

    XML

    <?xml version="1.0" encoding="utf-8"?>

    <rotate 

        android:fromDegrees="0"

        android:pivotX="50%"

        android:pivotY="50%"

        android:toDegrees="360">

        <shape

            android:innerRadiusRatio="3"

            android:shape="ring"

            android:thicknessRatio="8"

            android:useLevel="false">

            <size

                android:width="76dip"

                android:height="76dip" />

            <gradient

                android:angle="0"

                android:endColor="#00ffffff"

                android:startColor="#447a29"

                android:type="sweep"

                android:useLevel="false" />

        </shape>

    </rotate>

    Step 3: Working with the activity_main.xml file

    • Go to the activity_main.xml file and refer to the following code. 
    • Open the activity_main.xml file and in the ProgressBar tag and set the drawable in indeterminateDrawable attribute. 
    • Below is the code for the activity_main.xml file.

    XML

    <?xml version="1.0" encoding="utf-8"?>

    <RelativeLayout 

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:padding="20dp">

        <ProgressBar

            android:id="@+id/ProgressBar01"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_centerInParent="true"

            android:indeterminate="true"

            android:indeterminateDrawable="@drawable/progress_bg"

            android:progress="0" />

        <Button

            android:id="@+id/show_button"

            android:layout_width="191dp"

            android:layout_height="wrap_content"

            android:layout_below="@id/ProgressBar01"

            android:layout_centerHorizontal="true"

            android:layout_marginTop="80dp"

            android:text="Progress Bar" />

    </RelativeLayout>

    Step 4: Working with the MainActivity.java file

    • Go to the MainActivity.java file and refer to the following code. 
    • Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

    Java

    import android.os.Bundle;

    import android.os.Handler;

    import android.widget.Button;

    import android.widget.ImageView;

    import android.widget.ProgressBar;

    import android.widget.TextView;

    import androidx.appcompat.app.AppCompatActivity;

    public class MainActivity extends AppCompatActivity {

        Handler handler = new Handler();

        public static Button button;

        public static TextView textView;

        public static ImageView img1, img2;

        @Override

        protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_main);

            final ProgressBar progressBar = findViewById(R.id.ProgressBar01);

            progressBar.getProgress();

        }

    }

    Output:

    Skip to content

    • ТВикинариум
    • Форум
    • Поддержка
    • PRO
    • Войти

    ФорумXpucT2022-08-18T02:06:35+03:00

    Вы должны войти, чтобы создавать сообщения и темы.

    Смена цвета прогресс-бара.

    Цитата: Vladimir от 12.12.2022, 20:14

    Добрый вечер. 

    Помогите, пожалуйста, убрать это ублюдское зелёное бельмо в Windows 10. В старых видео @XpucT видел, что он решал эту проблему. 

    Добрый вечер. 

    Помогите, пожалуйста, убрать это ублюдское зелёное бельмо в Windows 10. В старых видео @XpucT видел, что он решал эту проблему. 

    Голосуйте — палец вниз.0Голосуйте — палец вверх.0

    Profile photo ofEject
    Голосуйте — палец вниз.0Голосуйте — палец вверх.1
    Profile photo ofYar
    Цитата: ЯR от 12.12.2022, 20:37

    Добрый вечер.
    В этом ответе имеется скрин с подробным описанием.

    Добрый вечер.
    В этом ответе имеется скрин с подробным описанием.

    Голосуйте — палец вниз.0Голосуйте — палец вверх.1
    Лучший способ помочь себе — помогать другим.

    Profile photo ofGarik
    Цитата: Игорь от 12.12.2022, 21:42

    Vladimir, приветствую 🖐
    В данном сообщении есть ответ на готовый вариант решения вопроса или же можно воспользоваться вариантом, который предложил ЯR.

    Vladimir, приветствую 🖐
    В данном сообщении есть ответ на готовый вариант решения вопроса или же можно воспользоваться вариантом, который предложил ЯR.

    Голосуйте — палец вниз.0Голосуйте — палец вверх.0
    От того что ты делаешь сегодня, зависит то, как ты будешь жить завтра.

    Цитата: Vladimir от 13.12.2022, 17:37

    Добрый вечер. Спасибо большое за советы! 
    Было бы круто если такая функция была в Pro версии Win10T, например в разделе «Персональные рекомендации». Если делать руками, есть погрешность на человеческий фактор, а так моментально и автоматически заменилось и все в порядке с системой. 

    Добрый вечер. Спасибо большое за советы! 
    Было бы круто если такая функция была в Pro версии Win10T, например в разделе «Персональные рекомендации». Если делать руками, есть погрешность на человеческий фактор, а так моментально и автоматически заменилось и все в порядке с системой. 

    Голосуйте — палец вниз.0Голосуйте — палец вверх.1

    Profile photo ofAndrey
    Цитата: Андрей от 13.12.2022, 19:49

    Vladimir, Добрый вечер.

    Win 10 Tweaker делает практически все твики только средствами Windows.
    А для реализации указанного изменения требуется сторонне приложение. Так что только сами.

    Vladimir, Добрый вечер.

    Win 10 Tweaker делает практически все твики только средствами Windows.
    А для реализации указанного изменения требуется сторонне приложение. Так что только сами.

    Голосуйте — палец вниз.0Голосуйте — палец вверх.1
    Голова дана человеку не для того, чтобы кушать, а для того, чтобы думать.

    Понравилась статья? Поделить с друзьями:

    Читайте также:

  • Как изменить цвет прицела пабг
  • Как изменить цвет прицела гта 5
  • Как изменить цвет прицела апекс
  • Как изменить цвет прицела half life
  • Как изменить цвет приложения инстаграм

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии