Android Gradient drawable programmatically

℡╲_俬逩灬. 提交于 2019-12-09 02:36:55

问题


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.

I want to generate something like this:


回答1:


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);     


来源:https://stackoverflow.com/questions/12427025/android-gradient-drawable-programmatically

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