For an XML only solution, you can create a layer-list
with two separate gradient
objects.
The following code creates two overlapping gradient
objects and uses centerY
with centerColor
to offset the black section. Here, the centerY
attributes are set to 0.9
and 0.1
, so the black color is restricted to the top and bottom 10% of the view height.
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<gradient
android:angle="90"
android:centerColor="@android:color/transparent"
android:centerY="0.9"
android:endColor="@android:color/black"
android:startColor="@android:color/transparent" />
</shape>
</item>
<item>
<shape>
<gradient
android:angle="90"
android:centerColor="@android:color/transparent"
android:centerY="0.1"
android:endColor="@android:color/transparent"
android:startColor="@android:color/black" />
</shape>
</item>
</layer-list>
For API level 23 or higher, the following solution will also work, using android:height
. This solution can work even if you don't know the total height of your view, as long as you know how large you want the gradient to be.
This code creates two separate gradients, each with a height of 60sp
, and then uses android:gravity
to float the gradients to the top and bottom of the view.
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:height="60sp"
android:gravity="top">
<shape android:shape="rectangle">
<gradient
android:angle="90"
android:endColor="@android:color/black"
android:startColor="@android:color/transparent" />
</shape>
</item>
<item
android:height="65sp"
android:gravity="bottom">
<shape android:shape="rectangle">
<gradient
android:angle="90"
android:endColor="@android:color/transparent"
android:startColor="@android:color/black" />
</shape>
</item>
</layer-list>
Thank you @Luksprog for the code help, and @thenaoh for the start of the idea.
The above solutions work and it is nice that they are pure XML. If your gradient is showing with stripes, you may want to try a programmatic solution, like shown in @lelloman's answer, to create a smoother gradient.