LayerDrawable以编程方式

时间:2013-11-21 12:13:21

标签: android drawable layerdrawable

由于我的应用程序的颜色主题是动态的,我只能使用颜色和shaperawables创建背景绘图, 我想构建一个可用颜色和形状绘制的edittext背景,如下所示。 但我想以编程方式执行此操作

如何以编程方式构建同样的drawable?

<item>
    <shape>
        <solid android:color="@android:color/yellow" />
    </shape>
</item>

<!-- main color -->
<item
    android:bottom="1dp"
    android:left="1dp"
    android:right="1dp">
    <shape>
        <solid android:color="@android:color/white" />
    </shape>
</item>

<!-- draw another block to cut-off the left and right bars -->
<item android:bottom="10dp">
    <shape>
        <solid android:color="@android:color/white" />
    </shape>
</item>

这是我试过的......

    GradientDrawable border = new GradientDrawable();
    border.setShape(GradientDrawable.RECTANGLE);
    border.setColor(Color.WHITE);

    GradientDrawable background = new GradientDrawable();
    background.setShape(GradientDrawable.RECTANGLE);
    background.setColor(Color.YELLOW);


    GradientDrawable clip = new GradientDrawable();
    clip.setShape(GradientDrawable.RECTANGLE);
    border.setColor(Color.WHITE);

    Drawable[] layers = {background, border, clip};
    LayerDrawable layerDrawable = new LayerDrawable(layers);

    layerDrawable.setLayerInset(0, 0, 0, 0, 0);
    layerDrawable.setLayerInset(1, 1, 0, 1, 1);
    layerDrawable.setLayerInset(2, 0, 0, 0, 10);

但结果不同....请帮助....!

2 个答案:

答案 0 :(得分:25)

我终于开始工作了。我没有使用GradientDrawable,而是使用ShapeDrawable

通过将此LayerDrawable设置为EditText背景,您可以重新生成默认EditText 自定义颜色的样式。

ShapeDrawable border = new ShapeDrawable();
border.getPaint().setColor(Color.WHITE);

ShapeDrawable background = new ShapeDrawable();
background.getPaint().setColor(Color.BLACK);


ShapeDrawable clip = new ShapeDrawable();
clip.getPaint().setColor(Color.WHITE);

Drawable[] layers = {background, border, clip};
LayerDrawable layerDrawable = new LayerDrawable(layers);

layerDrawable.setLayerInset(0, 0, 0, 0, 0);
layerDrawable.setLayerInset(1, 1, 0, 1, 1);
layerDrawable.setLayerInset(2, 0, 0, 0, 10);

答案 1 :(得分:0)

这也适用于Gradient Drawables:

GradientDrawable border = new GradientDrawable();
border.setColor(Color.White);

GradientDrawable background = new GradientDrawable();
background.setColor(Color.Black);

GradientDrawable clip = new GradientDrawable();
clip.setColor(Color.White);

GradientDrawable[] layers = {background, border, clip};
LayerDrawable layerDrawable = new LayerDrawable(layers);

layerDrawable.setLayerInset(0, 0, 0, 0, 0);
layerDrawable.setLayerInset(1, 1, 0, 1, 1);
layerDrawable.setLayerInset(2, 0, 0, 0, 10);