Android5.0以下drawable tag vector錯誤的解決辦法


Android5.0以下drawable tag vector錯誤的解決辦法

在Androi 5.0以下的設備可能會報這樣的錯誤:

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

解決思路:

1、首先檢查兼容性環境配置是否正確,判斷是否是環境配置的問題導致出現以上問題的,如果是,請配置好環境,如果不是
請看步驟2

兼容性環境的配置:

(1)首先在使用時,我們需要添加依賴:

compile 'com.android.support:support-vector-drawable:26.1.0'

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

(2)打開該模塊下的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"
}

(3) 修改布局文件app:srcCompat="@drawable/ic_egg05_got"

(4) 在Activity的oncreate中加入如下代碼即可: AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);

2、判斷不是兼容性環境配置的問題,檢查使用的控件

(1) ImageView,如果加載vector drawable資源的Activity是繼承自AppCompatActivity,xml使用ImageView,否則xml中使用AppCompatImageView
,同時android:src=" ";由app:srcCompat=" ";替代

(2)當在非ImageView控件中(Button、TextView等)作為Background、CompoundDrawable時,需要在Activity中加入以下聲明:

static {
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}

另外,如果直接在xml布局文件中使用,則必須使用selector、layer-list這種容器包裹起來,不能直接使用 (在代碼中設置不需要)

例如:

selector_drawable文件

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="30dp"
        android:height="30dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#cccccc"
        android:pathData="M8.59,16.34l4.58,-4.59 -4.58,-4.59L10,5.75l6,6 -6,6z"/>
    <!--android:fillColor="#FFC7C7CC"-->

</vector>

selsetor文件

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/selector_drawable"/>
</layer-list>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/selector_drawable"/>
</selector>

xml文件(以Button為例,其他控件正常替換即可)

<Button
        android:id="@+id/radioButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Button"
        android:textSize="@dimen/text_size_20"
        android:drawableRight="@drawable/selector"
        />

(3)若TextView,我們還可以通過重寫TextView解決android5.0以下機型崩潰問題,因為AppCompatTextView是沒有對CompoundDrawable進行適配的,如果直接使用android:drawableRight=" "等屬性加載矢量圖,Android5.0以下的
機型可能會出現崩潰,我們需要重寫TextView以及它的相關屬性。可以參考https://github.com/woxingxiao/VectorCompatTextView重寫TextView


免責聲明!

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



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