android - 以编程方式创建进度图

标签 android drawable

我有一个场景,我需要有大量的进度条可绘制对象。我无法为所有这些资源创建 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>

最佳答案

根据 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 创建的可绘制对象。

关于android - 以编程方式创建进度图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18011075/

相关文章:

android - XML 资源文件未在 Android 中复制

android - Facebook Android SDK,UiLifecycleHelper StackOverflow 错误

android - 垂直TextView在Android中占用太多空间

android - 错误 :Unknown host 'maven.fabric.io' . 您可能需要调整 Gradle 中的代理设置

android - 如何在文本中设置背景图像

java - 我的类(class)代码中已弃用的 API 在哪里?我想不通

java - Android Drawable getTransparentRegion() 不工作

java - Android 蓝牙 ConnectThread 示例错误?

Android Adwhirl 显示不支持的配给类型

java - XmlPullParserException 不受支持的功能