Android Gradient on Lollipop not working. - API 21

2019-01-19 00:37发布

问题:

When I try to use Gradient on Lollipop, it doesnt work. While it works on all previous versions.

Here is my example:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient android:type="radial" android:gradientRadius="500"
    android:startColor="#00417e" android:endColor="#001b34" />

回答1:

It is a bug. Check this here: https://code.google.com/p/android/issues/detail?id=77862



回答2:

I had the same problem and created 2 different files:

in drawables

android:gradientRadius="270"

and in drawables-v21

android:gradientRadius="270dp"

Now it works fine.



回答3:

int sdk = android.os.Build.VERSION.SDK_INT;
    if (sdk < Build.VERSION_CODES.LOLLIPOP) {
        //in your gradient use android:gradientRadius="500"
    } else {
      // in your gradient use android:gradientRadius="80%p" or 
      // android:gradientRadius="200dp"

Try write two different xml files using different gradientRadius style



回答4:

Seems I found another workaround - set gradient background in code:

findViewById(R.id.bg).setBackground(ContextCompat.getDrawable(context,R.drawable.bg_gradient));


回答5:

use like this will be fine:

android:gradientRadius="50%p"