【问题标题】:Create custom ProgressBar drawable programmatically以编程方式创建自定义 ProgressBar 可绘制对象
【发布时间】:2021-11-06 12:49:54
【问题描述】:

我需要以编程方式更改水平进度条的颜色。 我需要用color 设置进度条,用backgroundColor 设置背景 所以我需要为我的进度条设置一个新的progressDrawable或更改现有的。

进度条xml:

    <ProgressBar
        android:id="@+id/pb_stat_value"
        style="@style/CustomProgressBar"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginEnd="@dimen/margin_prog_bar_medium"
        android:layout_weight="5" />

CustomProgressBar 风格:

<style name="CustomProgressBar" parent="android:Widget.ProgressBar.Horizontal">
    <item name="android:indeterminateOnly">false</item>
    <item name="android:progressDrawable">@drawable/custom_progress_bar_horizontal</item>
    <item name="android:minHeight">@dimen/height_progress_bar_medium</item>
    <item name="android:maxHeight">@dimen/height_progress_bar_large</item>
</style>

我需要引用的custom_pogress_bar_horizzontal.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background">
        <shape android:shape="rectangle" >
            <solid android:color="@color/white" />
        </shape>
    </item>
    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <solid android:color="@color/black" />
            </shape>
        </clip>
    </item>
</layer-list>

我正在尝试使用此代码,但我只得到背景:

            val shape = GradientDrawable()
            shape.shape = GradientDrawable.RECTANGLE
            shape.setColor(backgroundColor)

            pbStatValue.progressDrawable = shape

【问题讨论】:

    标签: android xml android-drawable android-progressbar


    【解决方案1】:

    我使用 Drawable 扩展来引述这一点:

    &lt;item android:id="@android:id/background"&gt;的翻译

    val item1 = GradientDrawable()
    item1.shape = GradientDrawable.RECTANGLE
    item1.setColor(Utils.lighten(backgroundColor, 0.13))
    

    &lt;item android:id="@android:id/progress"&gt;的翻译

    val shape = GradientDrawable()
    shape.setColor(color)
    val item2 = ClipDrawable(shape, Gravity.START, ClipDrawable.HORIZONTAL)
    

    合并 Drawable:

    val array = arrayOf(item1, item2)
    val listDrawable = LayerDrawable(array)
    

    将其分配给可绘制的进度条

    pbStatValue.progressDrawable = listDrawable
    

    【讨论】:

    • 请在您的回答中提供更多详细信息。正如目前所写的那样,很难理解您的解决方案。
    • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多