Android Studio使用Vector Asset的注意事項


Vector是Android 5.0之后新增加的一項特性,目前已經可以兼容到Android 5.0之前的版本。但使用過程中依然還是可能產生一些兼容性的問題。

1、Android Studio創建Vector Asset

res目錄下的drawable目錄上單擊右鍵,選擇New --> Vector Asset,彈出Asset Studio對話框。
目前有兩種方式創建vector資源,一種是通過Material Icon生成vector資源,一種是通過SVG或PSD文件生成vector資源。具體操作過程比較簡單,不再詳述。

Asset Studio

注意:最好將生成的vector drawable資源放在drawable目錄下或drawable-anydpi目錄下。

2、兼容問題解決

如果使用的Android Studio版本為2.2以上,gradle版本也較新,生成的vector drawable資源也放在了drawable目錄下或drawable-anydpi目錄下,則一般就直接可以兼容Android 5.0之前操作系統。

vector drawable資源的使用方式如下,ic_egg05_got.xml為生成的vector 資源。

<ImageView
    android:id="@+id/ivVector"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_egg05_got"/>

如果不滿足以上的條件或由於其他原因導致Android 5.0之前的設備無法使用vector資源,也有別的解決辦法。

如果設備無法使用vector資源,則會導致應用崩潰,異常信息大致如下所示:

Caused by: android.view.InflateException: Binary XML file line #11: Error inflating class ImageView

Caused by: android.content.res.Resources$NotFoundException: File res/drawable-nodpi-v4/egg01_got.xml from drawable resource ID #0x7f020053

Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #2: invalid drawable tag vector

2.1、修改build.gradle

打開該模塊下的build.gradle文件。

  • 如果當前使用的gradle版本為2.0以上,在android節點下的defaultConfig節點下加入一行代碼:
vectorDrawables.useSupportLibrary = true
  • 如果使用的gradle版本為2.0以下,1.5以上,則需要在android節點下的defaultConfig節點下加入如下一行代碼:
generatedDensities = []

並在android節點下,defaultConfig節點后面加入

aaptOptions {
	additionalParameters "--no-version-vectors"
}

推薦使用較新的gradle版本以免不必要的麻煩。

之后,在dependencies中引入appcompat-v7兼容包,版本需要23.2以上。

compile 'com.android.support:appcompat-v7:25.0.1'

2.2、修改布局文件

如果在布局文件中使用了vector drawable資源的話,則需要修改其使用方式為:

app:srcCompat="@drawable/ic_egg05_got"

需要在根布局中引入命名空間xmlns:app="http://schemas.android.com/apk/res-auto"

2.3、修改Activity

需要將加載vector drawable資源的Activity繼承自AppCompatActivity


做完以上工作之后,Android 5.0之前的設備就可以支持使用vector drawable資源了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM