Unable to include in AnimatedVectorDrawableCompat in Nougat

This is my build.gradle

defaultConfig { ... minSdkVersion 21 targetSdkVersion 26 vectorDrawables.useSupportLibrary = true } 

and part of the layout

 <ImageView android:id="@+id/recents" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="?attr/selectableItemBackground" android:clickable="true" android:scaleType="fitCenter" app:srcCompat="@drawable/anim_test"/> 

and cast class:

 val np = convertView.findViewById<ImageView>(R.id.recents) val anim = np.drawable as AnimatedVectorDrawableCompat 

This works as expected on Lolipop (sdk 21), but Noug says with an error:

 android.graphics.drawable.AnimatedVectorDrawable cannot be cast to android.support.graphics.drawable.AnimatedVectorDrawableCompat 

What I do not get is why it returns AnimatedVectorDrawableCompat at SDk level 21 at all when AnimatedVectorDrawable is already supported by the system. And why does it return AnimatedVectorDrawable to Nougat, despite the indication of vectorDrawables.useSupportLibrary = true .

+5
source share
2 answers

I deal like this:

 public class MainActivity extends AppCompatActivity { ImageView img; Button show,play,stop; AnimatedVectorDrawableCompat anim_show,anim_play,anim_stop; Object canim_show,canim_play,canim_stop; static { AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); img = findViewById(R.id.img); show = findViewById(R.id.show); play = findViewById(R.id.play); stop = findViewById(R.id.stop); if(Build.VERSION.SDK_INT<21){ anim_show = (AnimatedVectorDrawableCompat) getResources().getDrawable(R.drawable.xunfei_show_animated_vector); anim_play = (AnimatedVectorDrawableCompat) getResources().getDrawable(R.drawable.xunfei_play_animated_vector); anim_stop = (AnimatedVectorDrawableCompat) getResources().getDrawable(R.drawable.xunfei_stop_animated_vector); }else{ canim_show = (AnimatedVectorDrawable) getResources().getDrawable(R.drawable.xunfei_show_animated_vector); canim_play = (AnimatedVectorDrawable) getResources().getDrawable(R.drawable.xunfei_play_animated_vector); canim_stop = (AnimatedVectorDrawable) getResources().getDrawable(R.drawable.xunfei_stop_animated_vector); } show.setOnClickListener(new View.OnClickListener() { @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override public void onClick(View view) { if(Build.VERSION.SDK_INT<21){ img.setImageDrawable(anim_show); anim_show.start(); }else{ img.setImageDrawable((AnimatedVectorDrawable) canim_show); ((AnimatedVectorDrawable)canim_show).start(); } } }); } } 
+3
source

Instead of doing checks with API<21 , you can use Animatable since AnimatedVectorDrawable and AnimatedVectorDrawableCompat implements it

 var anim = mImageView.drawable as Animatable anim.start() 
0
source

Source: https://habr.com/ru/post/1271879/


All Articles