Android4.4 及以下TextView,Button等控件使用矢量圖報錯

日常夜拍

1 問題描述

最近項目開發中,圖標資源我儘量使用了矢量圖,然而配置了基本的兼容設置,程序在低版本中運行還是出現了問題。

xml佈局文件中,在TextView中使用矢量圖,比如android:drawableStart,android:drawableStart這些屬性直接引用矢量圖資源。這樣在Android5.0及以上是沒問題的,但是5.0以下就拋出找不到圖片資源的問題。

2 原因

support庫並沒有爲AppcompatTextView,AppcompatButton等控件適配設置矢量圖屬性,反正我就記得ImageView,ImageButton有srcCompat屬性就是適配了的。

3 解決方案

基礎配置(必須):

1 在gradle里加上vectorDrawables 兼容支持

android {
    ...
    defaultConfig {
        ...
       vectorDrawables.useSupportLibrary = true 
    }
    ...
}

2 在Application或者Activity上加上AppCompateDelegate開啓CompatVectorFromResources支持

    /**
     * vector兼容5.0以下系統
     */
    static {
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion < 21){
            //適配android5.0以下
            AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
        }
    }

方案1:矢量圖包裝爲selector

如果將就Android4.4,Button就不能用矢量圖,要用位圖,那還叫錘子的兼容支持,我也不知道Google官方爲毛不在兼容控件上多加幾個支持屬性。

參考stackOverFlow的回答,Button,TextView,應用矢量圖,保險的是先把矢量圖轉爲selector,然後selector代替矢量圖使用,我覺得這是最佳的辦法。

例如:

  <Button
        style="@style/SettingItemTheme"
        android:layout_width="match_parent"
        android:layout_height="@dimen/setting_item_height"
        android:text="@string/my_setting"
        android:id="@+id/my_btn_setting"
        android:drawableStart="@drawable/selector_setting"
        android:drawableEnd="@drawable/selector_right"/>

selector_setting.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_my_setting"/>
</selector>

這裏android:drawableStart,android:drawableEnd,我引用的是selector,但是selector裏面就是一個默認的矢量圖,但用這種方式佈局,在Android4.4下運行程序就不會報錯。

方案2:不支持的就使用位圖

如果項目做了大半,突然說之前的矢量圖不能用,要改爲位圖,這是很崩潰的。

4 擴展:爲什麼我要用矢量圖,而不是位圖

最常見的設置界面:

我不知道各位實現設置Item的方式是怎樣的,我實現UI的原則是能用一個控件實現就用一個實現,所以Item我用一個Button控件就實現了。Button,TextView自帶drawableStart屬性,可以在上下左右放圖標,所以何必要用LinearLayout包三個控件實現呢。

例如:

    <Button
        style="@style/SettingItemTheme"
        android:layout_width="match_parent"
        android:layout_height="@dimen/setting_item_height"
        android:text="@string/my_vehicle_manage"
        android:id="@+id/my_btn_vehicle_manage"
        android:drawableStart="@drawable/selector_vehicle_manage"
        android:drawableEnd="@drawable/selector_right"/>

但是如果drawableStart引用的是位圖,這樣圖標的大小就很難調節,總是要找設計師重新切圖,麻煩。但是用vector向量圖就可以通過android:width,android:height調大小,這對開發來說很方便。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章