I'm creating a radial gradient like:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<gradient
android:startColor="#7faacaFF"
android:endColor="#cfe1edFF"
android:gradientRadius="326"
android:type="radial"/>
</shape>
But in the gradientRadius field using values like sp and dip return an error. Is there a way to specify the radius and scale for mdpi and scale it automatically in the rest of screen densities, or is necessary to create multiple drawable files?
Old question, but this answer shows highly ranked in Google and I belief an alternative approach is more scaleable. Instead of having to supply the dimension for every density, create a density-independent dimension from XML:
<dimen name="gradient_radius">25dp</dimen>
Since we cannot apply this directly to the radial gradient XML drawable, we have to apply in from code:
((GradientDrawable) someView.getBackground())
.setGradientRadius(getResources().getDimension(
R.dimen.yellowbadge_largeradius));
This overrides the android:gradientRadius
field, so you can leave that to 0. You can still not use a (screen based or otherwise) % dimension, though. I apply this to the background of my view (to which the gradient drawable is already set!) but it applies to an ImageView's src element as well, of course.
So what if you do this:
res/drawable/foo.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#7faacaFF"
android:endColor="#cfe1edFF"
android:gradientRadius="@dimen/radius"
android:type="radial"/>
</shape>
res/values-mdpi/dimens.xml
<resources ...>
...
<item name="radius" format="float" type="dimen">326</item>
....
</resources>
res/values-hdpi/dimens.xml
<resources ...>
...
<item name="radius" format="float" type="dimen">200.34</item>
....
</resources>
What do you think?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With