天天看點

androidStudio 中使用矢量圖

親測環境

  • classpath 'com.android.tools.build:gradle:2.3.1'

  • compileSdkVersion 
       buildToolsVersion "25.0.0"
    defaultConfig {
        minSdkVersion 
        targetSdkVersion 
        versionCode 
        versionName "1.0"
       vectorDrawables.useSupportLibrary = true
    }
               

Activity 繼承AppcompatActivity

1.可以正常的使用ImageView

<ImageView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       app:srcCompat="@drawable/ic_wc_black_24dp"
       />
           

2.但是無法使用

android:background="@drawable/ic_wc_black_24dp"

設定背景,可以在代碼中進行設定:

Resources resources = getResources();
        Resources.Theme theme = getTheme();
        Drawable drawable = VectorDrawableCompat.create(resources, R.drawable.ic_wc_black_24dp, theme);
findViewById(R.id.ttt).setBackground(drawable);
           

3.在這種情況下是可以使用AppCompatImageView和AppCompatImgaeButton.

<android.support.v7.widget.AppCompatImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:srcCompat="@drawable/ic_wc_black_24dp"
            />
    <android.support.v7.widget.AppCompatImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/ic_wc_black_24dp"
        />
           

但是僅限于這兩種原生控件,在其他非src的場景下,有兩種方法可以設定,第一種:就隻能按照上述方法在代碼中動态的設定。第二種:将矢量圖用drawable容器(如StateListDrawable, InsetDrawable, LayerDrawable, LevelListDrawable, 和RotateDrawable)包裹起來使用,否則會在低版本的情況下報錯。

Activity沒有繼承AppCompatActivity時

此時要使用ImageView和ImageButton 就隻能使用使用AppCompatImageView和AppCompatImageButton了。使用方法依然同上。其他的情況隻适用于代碼中擷取到Drawable之後再設定的情況。

在該種情況下即使将矢量圖包裹到Drawable容器裡,也無法使用。ImageView和ImageButton使用srcCompat會被直接忽略掉。

親測在該環境裡沒有生成相對應的png圖檔

聽一部分資料說明,會在build裡生成相應的png圖檔,但是在該種環境下,并沒有生成相應的圖檔,懷疑與什麼地方的配置有關。