Android ProgressBar: how to set secondary color programmatically

让人想犯罪 __ 提交于 2019-12-21 09:29:51

问题


I need to set secondary progress bar color programmatically.

I only see the method

ProgressBar.setProgressDrawable(drawable)

for set the primary color, but there isn't a method for set the secondary color.

How I can do it?


回答1:


ProgressBar.getProgressDrawable() returns a LayerDrawable in which:

LayerDrawable progressDrawable = (LayerDrawable) getProgressDrawable();
Drawable backgroundColor = progressDrawable.getDrawable(0);
Drawable secondaryColor = progressDrawable.getDrawable(1);
Drawable primaryColor = progressDrawable.getDrawable(2);

I try to modify the colors whit (example):

progressDrawable.setDrawableByLayerId(progressDrawable.getId(2), new ClipDrawable(...));

but sometimes the screen freeze, sometimes crash. Finally I abandoned the search for lack of time. Sorry :(

Michele




回答2:


The drawable you specify using setProgressDrawable has background, primary and secondary drawables in it. Here is an example of ProgressBar drawable that is shipped with android:

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

    <item android:id="@android:id/background">
        <shape>
            <corners android:radius="5dip" />
            <gradient ...  />
        </shape>
    </item>

    <item android:id="@android:id/secondaryProgress">
        <clip>
            <shape>
                <corners android:radius="5dip" />
                <gradient .../>
            </shape>
        </clip>
    </item>

    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <corners android:radius="5dip" />
                <gradient ...  />
            </shape>
        </clip>
    </item>

</layer-list> 



回答3:


Probably not relevant to Michele, but perhaps it will help someone else..

ProgressBar progress = (ProgressBar) fullView.findViewById(R.id.main_progressbar);
LayerDrawable progressDrawable = (LayerDrawable)progress.getProgressDrawable();
Drawable drawable = activity.getResources().getDrawable(R.drawable.WHATEVER_YOU_WANT);
ClipDrawable cd = new ClipDrawable(drawable, Gravity.LEFT,ClipDrawable.HORIZONTAL);
progressDrawable.setDrawableByLayerId(android.R.id.progress, cd);



回答4:


Check this

You can use a drawable xml like this to set progressdrawable

<item android:id="@android:id/background"
    android:drawable="@drawable/progress_bar_nor">       
</item>    
<item android:id="@android:id/secondaryProgress"
    android:drawable="@drawable/progress_bar_nor">       
</item>
<item
    android:id="@android:id/progress"
    android:drawable="@drawable/progress_bar_sel"/>

Refer this link

https://stackoverflow.com/a/27144594/1554031



来源:https://stackoverflow.com/questions/6235890/android-progressbar-how-to-set-secondary-color-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!