2017-09-17 114 views
4

這是我的build.gradle無法投射到AnimatedVectorDrawableCompat在牛軋糖

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

和佈局

<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"/> 

的一部分,該類投:

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

這可以作爲預計在Lolipop(sdk 21),但牛軋糖失敗說:

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

我沒有得到的是,爲什麼當系統已經支持AnimatedVectorDrawable時,爲什麼它會在sdk level 21上返回AnimatedVectorDrawableCompat?爲什麼它會返回Nougat中的AnimatedVectorDrawable,儘管指定了vectorDrawables.useSupportLibrary = true

+1

同樣的問題。通過解決方法解決:運行時的條件 - 您需要爲棒棒糖和更高版本投射AnimatedVectorDrawable,之前棒棒糖投射AnimatedVectorDrawableCompat。 – Fllo

回答

2

我處理這樣的:與支持庫26.0.1

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(); 
       } 

      } 
     }); 





    } 
} 
相關問題