Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

android - LayerDrawable programmatically

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I finally got it working. Instead of using GradientDrawable I used ShapeDrawable.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...