0

I have to set background of this to many views with different colors. but if I make it so, the xml will be around 20 files, which is huge, so I want to convert the following xml layer-list into progmatical way into fully independent module without even a single xml, so that it can be reusable, please help me guys.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    //i can create this drawable
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#ff2632"/>
        </shape> </item>

    //I don't know how to achieve this one, especially this "bottom property"
    <item android:bottom="2dp">
        <shape android:shape="rectangle">
            <solid android:color="#d7ffa2"/>
        </shape> </item>
</layer-list>
12
  • Which color you want to change? Commented Dec 18, 2015 at 9:56
  • @NigamPatro,<item android:bottom="2dp"> <shape android:shape="rectangle"> <solid android:color="#d7ffa2"/> </shape> </item> Commented Dec 18, 2015 at 9:58
  • @NigamPatro,basically i have to set this xml as background to may views with different color codes Commented Dec 18, 2015 at 9:58
  • Mean, the bottom part? Commented Dec 18, 2015 at 10:00
  • Possible duplicate of Android - How to change a layer-list drawable? Commented Dec 18, 2015 at 10:00

1 Answer 1

4

Please find the below code,

// This is the first item in your XML file
GradientDrawable layer1 = new GradientDrawable();
layer1.setShape(GradientDrawable.RECTANGLE);
layer1.setColor(Color.parseColor("#ff2632"));

// This is your second item in your XML file
GradientDrawable layer2 = new GradientDrawable();
layer2.setShape(GradientDrawable.RECTANGLE);
layer2.setColor(Color.parseColor("#d7ffa2"));

// This will give the bottom space which you are unable to do    
InsetDrawable insetLayer2 = new InsetDrawable(layer2, 0, 0, 0, 2);

// This is the final drawable which is to be used
LayerDrawable layerDrawable = new LayerDrawable(new Drawable[]{layer1, insetLayer2});

Refer this, and let me know for issues.

Sign up to request clarification or add additional context in comments.

8 Comments

buddy where u had used the ,<item android:bottom="2dp"> property
The insetLayer2 is doing this task.
would you explain the above in detail, so that i can understand
Which part you are unable to understand? Please go through the comments.
new LayerDrawable(new Drawable[]{layer1, insetLayer2});
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.