Android Gradient drawable programmatically
22,294
Found the answer!. Possible duplicate Multi-gradient shapes.
Replaced:
backColor.setBounds(0, 0,0, 4);
shadow.setBounds(0,98, 0, 0);
for
layerList.setLayerInset(0, 0, 0, 0, 4);
layerList.setLayerInset(1, 0, 98, 0, 0);
Author by
marbarfa
Updated on July 09, 2022Comments
-
marbarfa almost 2 years
I have a gradient drawable defined in xml that I use it as a background, like this:
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:bottom="4dp"> <shape> <gradient android:startColor="@color/blue" android:endColor="@color/dark_blue" android:angle="270" /> </shape> </item> <item android:top="98dp"> <shape> <gradient android:startColor="@color/black" android:endColor="@color/transparent_black" android:angle="270" /> </shape> </item> </layer-list>
I need to implement this programmatically. I have tried to use a GradientDrawable as follows (this method is implemented on a custom view):
int[] colors1 = {getResources().getColor(R.color.black), getResources().getColor(R.color.trasparent_black)}; GradientDrawable shadow = new GradientDrawable(Orientation.TOP_BOTTOM, colors1); shadow.setBounds(0,98, 0, 0); int[] colors = new int[2]; colors[0] = getResources().getColor(R.color.blue); colors[1] = getResources().getColor(R.color.dark_blue); GradientDrawable backColor = new GradientDrawable(Orientation.TOP_BOTTOM, colors); backColor.setBounds(0, 0,0, 4); //finally create a layer list and set them as background. Drawable[] layers = new Drawable[2]; layers[0] = backColor; layers[1] = shadow; LayerDrawable layerList = new LayerDrawable(layers); setBackgroundDrawable(layerList);
The problem is that it seems that setting the bounds is useless or doesn't work the same way as (android:top, android:bottom xml parameters). The resulting background is each layer painted from top to bottom, one above the other.