Search code examples
androidactionbarsherlockandroid-actionbarshapedrawable

Dynamically change action bar divider color (android:bottom for programmatically generated ShapeDrawable)?


I'm trying to change the color of the divider bar at the bottom of the action bar programmatically. My strategy is to set the action bar background to a programmatically generated LayerDrawable containing ShapeDrawable rectangles, based on this XML:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Bottom Line -->
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/action_bar_line_color" />
        </shape>
    </item>

    <!-- Color of your action bar -->
    <item android:bottom="2dip">
        <shape android:shape="rectangle">
            <solid android:color="@color/action_bar_color" />
        </shape>
    </item>
</layer-list>

But I've hit a roadblock: I can't figure out how to apply an android:bottom property (as in <item android:bottom="2dip">) programmatically. Obviously android:bottom is a property of the item tag, to which (I think) there's no programmatic equivalent, and I haven't been able to find any methods/properties of ShapeDrawable that look appropriate.

Code so far:

public LayerDrawable createABBackground(String color) {
    ShapeDrawable rect = new ShapeDrawable(new RectShape());
    rect.getPaint().setColor(Color.parseColor("#000000"));
    ShapeDrawable rect2 = new ShapeDrawable(new RectShape());
    rect2.getPaint().setColor(Color.parseColor(color));
    ShapeDrawable[] layers = {rect, rect2};
    LayerDrawable background = new LayerDrawable(layers);
    return background;
}

Ideas? If it matters for alternative solutions, I'm using ActionBarSherlock.

EDIT:

setLayerInset, as suggested by MH, did what I wanted. Here's a modified version of the function using it:

public LayerDrawable createABBackground(String color) {
    ShapeDrawable rect = new ShapeDrawable(new RectShape());
    rect.getPaint().setColor(Color.parseColor(color));
    ShapeDrawable rect2 = new ShapeDrawable(new RectShape());
    rect2.getPaint().setColor(Color.parseColor("#000000"));
    ShapeDrawable[] layers = {rect, rect2};
    LayerDrawable background = new LayerDrawable(layers);
    background.setLayerInset(0, 0, 3, 0, 0);
    background.setLayerInset(1, 0, 0, 0, 3);
    return background;
}

Solution

  • As per earlier comment:

    Did you give setLayerInset(int index, int l, int t, int r, int b) a try? The docs say:

    Specify modifiers to the bounds for the drawable[index]. left += l top += t; right -= r; bottom -= b;