【问题标题】:Change color of progress bar background in android在android中更改进度条背景的颜色
【发布时间】:2016-10-07 13:47:03
【问题描述】:

我有一个进度条,它的外观是在 xml 文件中定义的:

<?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="@dimen/round_corners_elements" />
            <solid android:color="@color/blue_50" />

            <stroke android:width="1px" android:color="@color/light_gray" />
        </shape>
    </item>

    <item android:id="@android:id/progress">
        <clip android:clipOrientation="horizontal" android:gravity="left">
            <shape>
                <corners
                    android:radius="@dimen/round_corners_elements"
                   />
                <solid android:color="@color/signaling_color" />
                <stroke android:width="1px" android:color="@color/light_gray" />
            </shape>
        </clip>
    </item>

</layer-list>

但由于我需要将背景颜色 (blue50) 动态更改为任何其他颜色,所以我失败了。有人知道我如何以编程方式更改它吗?进度可以保持原样。比较特别的是,进度条有圆角,这是必须的。我尝试了几种方法,但没有一个对我有用。

setBackgroundTintList 不起作用,因为只有 >API21

可用
int[][] states = new int[][] { new int[] { android.R.attr.background }, new int[] { -android.R.attr.process } };
int[] colors = new int[] { Color.parseColor("#000000"), Color.BLACK };
ColorStateList myList = new ColorStateList(states, colors);
progressBar.setBackgroundTintList(myList);
progressBar.setBackgroundTintMode(PorterDuff.Mode.SRC_OVER);

setBackgroundColor 也没有效果:

 progressBar.setBackgroundColor(ContextCompat.getColor(this, R.color.white));

有人有想法吗?

【问题讨论】:

  • 更改为 color.xml 中定义的任何其他颜色
  • 您是否将此 xml 可绘制对象设置为 progressDrawable 属性?
  • 是的,它在 Layouter 的 progressDrawable 标记中设置为可绘制对象。我需要以编程方式设置它。我不帮我在编译时设置它。

标签: android xml progress-bar


【解决方案1】:

您必须获得ProgressBar 使用的LayerDrawable,然后

如果我没记错的话,&lt;shape&gt; 标签会导致系统在运行时创建一个GradientDrawable,并且很方便地具有setColor() 之类的方法

【讨论】:

  • 解决了这个问题。我使用了第一个版本的运行时。
【解决方案2】:
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        progressBar.setProgressBackgroundTintList(ColorStateList.valueOf(tint));
    } else {
        LayerDrawable drawable = (LayerDrawable) progressBar.getProgressDrawable();
        Drawable background = new ColorDrawable(tint);
        drawable.setDrawableByLayerId(android.R.id.background, background);
        progressBar.setProgressDrawable(drawable);
    }

【讨论】:

    猜你喜欢
    • 2014-07-15
    • 2020-01-20
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多