Reputation: 32253
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?
Upvotes: 16
Views: 5072
Reputation: 2072
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.
Upvotes: 8
Reputation: 1765
Use percentages, in the android:gradientRadius field.
Example:
For a 50% radious set to 50000%p
<gradient
android:angle="45"
android:centerX="0.5"
android:centerY="0.5"
android:endColor="#123123"
android:gradientRadius="50000%p"
android:startColor="#456456"
android:type="radial" />
Upvotes: -2
Reputation: 10184
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?
Upvotes: 22
Reputation: 3327
The docs say that you can specify the gradientRadius attribute as a float (guessing that it would mean px) or as fraction.
May be a fractional value, which is a floating point number appended with either % or %p, such as "14.5%". The % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to some parent container.
Have you tried that? That would make it possible to specify the size in dp or whatever unit in the layout, and refer to it from here. It is strange though, most sizes are specified as dimensions in the drawable xml format.
Upvotes: 0