How to change the ProgressBar color in a widget?

2019-04-13 06:22发布

问题:

Is there any way to change the color of the ProgressBar residing in the app widget at runtime?

This is how the ProgressBar progress value is updated:

RemoteViews views = new RemoteViews( context.getPackageName(), R.layout.widget );
views.setProgressBar( R.id.progressbar, 100, 10, false );
...
appWidgetManager.updateAppWidget( widgetID, views );

Unfortunately, the RemoteViews class does not allow us to set a color filter or even a different progress drawable for ProgressBar.

Any ideas would be appreciated.

回答1:

I have encountered with similar problem to tint ProgressBar inside custom notification layout. I have managed to do it using reflection API:

    Method setTintMethod = null;
    try {
        setTintMethod = RemoteViews.class.getMethod("setProgressTintList", int.class, ColorStateList.class);
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }
    if (setTintMethod != null) {
        try {
            setTintMethod.invoke(mYourRemoteViews, R.id.your_progress_bar_id, ColorStateList.valueOf(yourColor));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }


回答2:

Add this line in the ProgressBar XML:

android:progressDrawable="@drawable/progressbar"

And now Create the progressbar.xml drawable:

<?xml version="1.0" encoding="utf-8"?>
<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="#33FF33"
                android:endColor="#008000"
                android:angle="270" />
        </shape>
    </clip>
</item>

</layer-list>

See reference: Android change Horizonal Progress bar color