How to set style to a progressBar programmatically on Android
Asked Answered
B

2

17

I have ProgressBar style in style.xml. When I create layout, put there ProgressBar and set style like:

style="@style/ProgressBarStyle"

set layout to dialog and all is fine.

Other way create view for dialog programmatically. So for ProgressBar I have next code:

new ProgressBar(context, null, R.style.ProgressBarStyle);

But in this way there is nothing instead ProgressBar.

P.S. I don't forget add ProgressBar to view which I set as dialog view.

Beastly answered 10/10, 2014 at 16:3 Comment(2)
So your problem is that your custom style isn't applied on your progress bar?Skep
isn't applied programmaticallyBeastly
P
23

You can set your style from the constructor, for instance:

progressBar = new ProgressBar(activity, null, android.R.attr.progressBarStyleSmall);

Where the third attribute is the style.

In your case, I think the error is to choose a wrong one. Just this.

Profane answered 10/10, 2014 at 16:22 Comment(3)
As I already wrote, I know about third attribute. If I choosed wrong one, why in xml this wrong one worked correctly?Beastly
Is it working for you? I'm not totally sure, but I would say that they are references for different things and that R.style.ProgressBarStyle is override by your own style (in styles folder) or even the default Android style you've set to the activityProfane
ok, maybe I expressed not clearly. I have my own style called ProgressBarStyle. in R.style and @style i can find it. In xml all right (style applied to progress bar). But programmatycally something wrong, any progress bar isn't shownBeastly
G
0

Figured it out. You have to pass the style through the 4th parameter defStyleRes not the 3rd parameter defStyleAttr.

ProgressBar customProgressBar = new ProgressBar(context, null, 0, R.style.Widget_App_CustomProgressBar);

Furthermore, the custom style you create should extend the AppCompat progress bar style as shown below.

<style name="Widget.App.CustomProgressBar" parent="Widget.AppCompat.ProgressBar">
    <item name="android:indeterminateOnly">false</item>
    <item name="android:progressDrawable">@drawable/custom_progress_bar</item>
</style>
Giuseppe answered 25/9, 2021 at 14:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.