Change bottom property of item of layer-list Drawable programmatically

时间秒杀一切 提交于 2019-12-10 14:46:51

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/31558705/change-bottom-property-of-item-of-layer-list-drawable-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!