【问题标题】:Create a progress drawable programmatically以编程方式创建进度可绘制对象
【发布时间】:2013-08-02 18:17:14
【问题描述】:

我有一个场景,我需要有大量的进度条可绘制对象。我无法为所有这些创建 xml 资源,因为我希望用户选择一种颜色,然后用于动态创建可绘制对象。下面是 xml 中的一个这样的可绘制对象,我如何以编程方式创建这个精确的可绘制对象?

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
    <shape>
        <solid android:color="@color/transparent" />
        <stroke android:width="2px" android:color="@color/category_blue_stroke"/>
    </shape>
</item>


<item android:id="@android:id/progress">
<clip>
    <shape>
        <solid android:color="@color/category_blue" />
        <stroke android:width="2px" android:color="@color/category_blue_stroke"/>
    </shape>
</clip>
</item>

</layer-list>

【问题讨论】:

标签: android drawable


【解决方案1】:

从 Rajesh 和 g00dy 提供的链接中,我想出了一个解决方案。

public static Drawable createDrawable(Context context) {

ShapeDrawable shape = new ShapeDrawable();
shape.getPaint().setStyle(Style.FILL);
shape.getPaint().setColor(
    context.getResources().getColor(R.color.transparent));

shape.getPaint().setStyle(Style.STROKE);
shape.getPaint().setStrokeWidth(4);
shape.getPaint().setColor(
    context.getResources().getColor(R.color.category_green_stroke));

ShapeDrawable shapeD = new ShapeDrawable();
shapeD.getPaint().setStyle(Style.FILL);
shapeD.getPaint().setColor(
    context.getResources().getColor(R.color.category_green));
ClipDrawable clipDrawable = new ClipDrawable(shapeD, Gravity.LEFT,
    ClipDrawable.HORIZONTAL);

LayerDrawable layerDrawable = new LayerDrawable(new Drawable[] {
    clipDrawable, shape });
return layerDrawable;
}

此代码将创建一个与我的问题中的 xml 创建的外观相似的可绘制对象。

【讨论】:

  • 您还应该通过layerDrawable.setId(...) 为层设置ID android.R.id.backgroundandroid.R.id.progress(如果需要,还有android.R.id.secondaryProgress)。
猜你喜欢
  • 2021-11-06
  • 1970-01-01
  • 2019-11-21
  • 2018-03-23
  • 1970-01-01
  • 1970-01-01
  • 2018-09-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多