androidlayer-listlayerdrawable

Change bottom property of item of layer-list Drawable programmatically


I am creating a LayerDrawable that creates bottom stroke but i dont know how to give bottom margin of a layer(Drawablw).

    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:bottom="2dp">
      ..
        </item>
    </layer-list>

I want to set bottom margin like above programmatically.

So far i have done this:

Drawable[] list = new Drawable[2];
GradientDrawable strokeDrawable = new GradientDrawable(
    GradientDrawable.Orientation.TOP_BOTTOM, new int[] {
        strokeColor[0], strokeColor[0] });
GradientDrawable backgroundDrawable = new GradientDrawable(
    GradientDrawable.Orientation.TOP_BOTTOM, bgColor);
// Now how to set bottom margin to make border. 

list[0] = strokeDrawable;
list[1] = backgroundDrawable;

LayerDrawable layerDrawable = new LayerDrawable(list);

Anyone know about this?


Solution

  • After a lot digging i found a solution, though it solved my problem but it is not what i was looking for.

    I created a layer-list drawable and changed its items color dynamically. Here is the code:

    <?xml version="1.0" encoding="utf-8"?>
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    
    <item android:id="@+id/item_bottom_stroke" >
        <shape android:shape="rectangle">
            <solid android:color="#0096FF"/>
        </shape>
    </item>
    <item android:id="@+id/item_navbar_background" android:bottom="1dp" >
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF"/>
        </shape>
    </item>
    

    Following code modifies above drawable at runtime to change its colors.

    LayerDrawable layerDrawable = (LayerDrawable) v.getContext().getResources().getDrawable(R.drawable.layer_list_navigation_with_border);
    GradientDrawable strokeDrawable = (GradientDrawable) layerDrawable.findDrawableByLayerId(R.id.item_bottom_stroke);
    strokeDrawable.setColor(strokeColor[0]);
    GradientDrawable backgroundColor = (GradientDrawable) layerDrawable.findDrawableByLayerId(R.id.item_navbar_background);
    backgroundColor.setColors(bgColor);
    

    posted solution, thought someone might get benefited.