I'm trying to create a shape drawable with radial gradient background, with radius that will adjust to the screen size (take a look at the relevant documentation).
This is my code:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<gradient
android:endColor="#000"
android:gradientRadius="50%p"
android:startColor="#5d2456"
android:type="radial" />
</shape>
But it doens't seem to work. if I remove the "%p", it works, but then the radius will be static, thus not adjusting to the screen size...Any idea what's wrong?
I ended up creating a custom View with following overriden onDraw method:
In your layout just add the View:
Of course it would be possible to create attributes for the View, eg. color, percentage to allow customization via XML.
From what I´ve tested, the
%
does work, but not as you expected.First of all
seems to take the value as pixels 50px
is converted as if 50% = 0.5 px, try
and you will see a 50px radius.
Using
%p
has a similar result. Obviously this is something I hope will be changed in the future, because it does not have much use as it is. Usually XML ShapeDrawable resources adapt their size to some external container, in this casegradientRadius
is setting the size regardless of the container.You could create a shape drawable at runtime similiar to this post https://stackoverflow.com/a/4943888/604504
This way you could calculate the percentage after retrieving the screen size.
Note that gradientRadius percentages do work in Lollipop. But if you have to support pre-Lollipop I expanded upon @marnaish's answer adding XML attributes. My gradientRadius is defined as a percentage of the parent view's width:
In attrs.xml:
Unfortunately you can't create an XML drawable from a custom class, so you can't set it as a View's android:background. The workaround is to use a FrameLayout to layer it as the background.