Change bottom property of item of layer-list Drawable programmatically
Asked Answered
M

2

6

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?

Multivocal answered 22/7, 2015 at 9:7 Comment(0)
M
5

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.

Multivocal answered 22/7, 2015 at 12:6 Comment(0)
P
5

This is an old question, but I figured I still post the answer here in case it helps someone.

The way to change bottom property of layer-list programmatically is by using layerDrawable.setLayerInset(index, left, top, right, bottom); in this question example:

LayerDrawable layerDrawable = (LayerDrawable) v.getContext().getResources().getDrawable(R.drawable.layer_list_navigation_with_border);
layerDrawable.setLayerInset(1, 0, 0, 0, bottom);

where bottom is pixel value of the desired dp.

Hope this helps someone.

Populous answered 25/10, 2018 at 17:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.