Android4.4 及以下TextView,Button等控件使用矢量图报错

发布时间:2019-06-27 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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就不能用矢量图,要用位图,那还叫锤子的兼容支持,我也不知道@R_512_1001@官方为毛不在兼容控件上多加几个支持属性。

参考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 >"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调大小,这对开发来说很方便。

脚本宝典总结

以上是脚本宝典为你收集整理的Android4.4 及以下TextView,Button等控件使用矢量图报错全部内容,希望文章能够帮你解决Android4.4 及以下TextView,Button等控件使用矢量图报错所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。