LayerDrawable编程LayerDrawable

2023-09-07 11:08:39 作者:港湾少女

由于我的应用程序的颜色主题是动态的,我只能创建使用颜色和shapedrawables背景可绘制 我想用色彩和形状打造的EditText背景绘制如下图所示。 但我想这样做编程

Since my application's color theme is dynamic i can only create background drawables using colors and shapedrawables, i want to build a edittext background drawable with colors and shapes as shown below. But i want to do this programatically

如何以编程方式建立同样的绘制?

How to build this same drawable programatically?

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

这是我尝试过......

this is what i tried....

    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);

但结果却是不同的......请大家帮忙....!

but the result is different....please help....!

推荐答案

我得到它的工作finaly ...而不是使用G​​radientDrawable我用ShapeDrawable ......多数民众赞成....:)

i got it working finaly... Instead of using GradientDrawable i used ShapeDrawable... thats all.... :)

通过设置这个layerDrawable作为一个EditText的背景,你可以重新生成默认的EditText 样式自定义颜色...

By setting this layerDrawable as an edittext background you can regenerate default edittext styles with custom colors...

 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);

`