2013-08-02 40 views
4

我有一个场景,我需要大量的进度条可绘制。我不能创建所有这些XML资源,因为我想让用户选择一种颜色,然后将用于动态创建绘图。下面是XML中的一个这样的drawable,我如何以编程方式创建这个精确的drawable?以编程方式创建可绘制的进度

<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> 
+2

This http://stackoverflow.com/a/8019888/1321873应该可以帮到你。 – Rajesh

+2

可能重复的[以编程方式创建自定义Seekbar(无XML)](http://stackoverflow.com/questions/14510343/create-custom-seekbar-programatically-no-xml) – g00dy

回答

13

从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的drawable。

+0

您还应该设置ids'android.R。 id.background'和'android.R.id.progress'(以及'android.R.id.secondaryProgress',如果需要的话)通过'layerDrawable.setId(...)'分层。 – kuelye

相关问题