Android SVG 兼容低版本API

在 Android 中使用 SVG 矢量图 来替代传统的图片有很多好处,比如自适应,体积小,不失真等。但是在 API21 以下版本使用时会有兼容性问题,在 Androi 5.0 以下的设备可能会报这样的错误:

......
Binary XML file line #1: invalid drawable tag vector
......
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/you_svg_name.xml from drawable resource ID #0x7f02004b
......

那要怎么做呢?

一、配置。

详细请查看 vector-asset-studio

参看下面的代码:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.example.app"
        minSdkVersion 16
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    buildToolsVersion '27.0.2'
}

androidExtensions {
    experimental = true
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:27.0.2'
    implementation 'com.android.support:design:27.0.2'
    implementation 'com.android.support:support-vector-drawable:27.0.2'
    implementation 'com.android.support:support-v4:27.0.2'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:animated-vector-drawable:27.0.2'
}

1: 添加依赖

implementation 'com.android.support:animated-vector-drawable:27.0.2'

2:在 defaultConfig 下面添加声明

android {
  defaultConfig {
    vectorDrawables.useSupportLibrary = true
  }
}

二、使用。

配置好了可以开始使用, 一般有两个场景,
一个是 TextView、EditText 的 drawableLeft、Right、Top、Bottom,
一个是作为 ImageView 背景 background。

  1. 用 srcCompat 代替 src.
  2. 设置背景 可以将你的 svg 资源用 selector 标签包裹起来调用。

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/your_svg_name"></item>
    </selector>
  3. 在 EditText 中使用 android:drawableLeft 和 android:drawableStart 时,有可能还会报错,这时你可以参照第二条使用。

     <EditText
        android:id="@+id/id_edit"
        style="@style/inputNameEt"
        android:drawableLeft="@drawable/drawable_home_selector"
        android:drawableStart="@drawable/drawable_home_selector"  />

    4. 有部分控件点击需要 selector,我贴出自己使用的 Image 以及 Color 的 selector:

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Non focused states -->
    <item android:drawable="@drawable/home_search_norm" android:state_focused="false" android:state_pressed="false" android:state_selected="false" />
    <item android:drawable="@drawable/home_search_sel" android:state_focused="false" android:state_pressed="false" android:state_selected="true" />
    <!-- Focused states -->
    <item android:drawable="@drawable/home_search_sel" android:state_focused="true" android:state_pressed="false" android:state_selected="false" />
    <item android:drawable="@drawable/home_search_sel" android:state_focused="true" android:state_pressed="false" android:state_selected="true" />
    <!-- Pressed -->
    <item android:drawable="@drawable/home_search_sel" android:state_pressed="true" android:state_selected="true" />
    <item android:drawable="@drawable/home_search_sel" android:state_pressed="true" />
    </selector>
    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Selected -->
    <item android:state_selected="true" android:color="@color/home_selected_color" />
    <!-- Active -->
    <item android:state_active="true" android:color="@color/home_selected_color"/>
    <item android:state_selected="false" android:color="@color/home_normal_color" />
    <item android:state_active="false" android:color="@color/home_normal_color"/>
    </selector>

    使用的时候,如需更换样式可调用 (使用场景如首页导航栏切换样式)

    public void setSelected(boolean selected);

以上。

三、自定义控件

对于 textview 的 drawableLeft,自己定义了一个可设置位置和大小的控件,有需要可以 copy。
下面贴出自定义过程和使用方法:

  1. 首先在应用 “res / values / attrs.xml” 的 attrs.xml 文件中添加自定义 TextView 属性:

    <declare-styleable name="CustomTextView">
        <attr name="drawable" format="reference"/>
        <attr name="drawableWidth" format="dimension"/>
        <attr name="drawableHeight" format="dimension"/>
        <attr name="position" format="integer"/>
    </declare-styleable>
  2. 然后像这样创建自定义的 TextView 类:

    import android.content.Context;
    import android.content.res.Resources;
    import android.content.res.TypedArray;
    import android.graphics.Canvas;
    import android.graphics.drawable.Drawable;
    import android.os.Build;
    import android.support.v7.content.res.AppCompatResources;
    import android.support.v7.widget.AppCompatTextView;
    import android.util.AttributeSet;
    import android.util.TypedValue;
    
    public class CustomTextViewextends AppCompatTextView {
    
        private Drawable mDrawable;//设置的图片
        private int mScaleWidth; // 图片的宽度
        private int mScaleHeight;// 图片的高度
        private int mPosition;// 图片的位置 1左2上3右4下
    
        public CustomTextView(Context context) {
            super(context);
        }
    
        public CustomTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
            init(context, attrs);
        }
    
        public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            init(context, attrs);
        }
    
        public void init(Context context, AttributeSet attrs) {
            TypedArray typedArray = context.obtainStyledAttributes(attrs,
                    R.styleable.CustomTextView);
            if (null != typedArray) {
    
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    mDrawable = typedArray.getDrawable(R.styleable.CustomTextView_drawable);
                } else {
                    int mDrawableId = typedArray.getResourceId(R.styleable.CustomTextView_drawable, -1);
                    if (mDrawableId != -1)
                        mDrawable = AppCompatResources.getDrawable(context, mDrawableId);
                }
                mScaleWidth = typedArray
                        .getDimensionPixelOffset(
                                R.styleable.CustomTextView_drawableWidth,
                                dip2px(context, 20));
                mScaleHeight = typedArray.getDimensionPixelOffset(
                        R.styleable.CustomTextView_drawableHeight,
                        dip2px(context, 20));
                mPosition = typedArray.getInt(R.styleable.CustomTextView_position, 3);
                typedArray.recycle();
            }
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            if (mDrawable != null) {
                mDrawable.setBounds(0, 0, mScaleWidth, mScaleHeight);
    
            }
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            switch (mPosition) {
                case 1:
                    this.setCompoundDrawables(mDrawable, null, null, null);
                    break;
                case 2:
                    this.setCompoundDrawables(null, mDrawable, null, null);
                    break;
                case 3:
                    this.setCompoundDrawables(null, null, mDrawable, null);
                    break;
                case 4:
                    this.setCompoundDrawables(null, null, null, mDrawable);
                    break;
                default:
                    break;
            }
        }
    
        public static int dip2px(Context context, int dpValue) {
            Resources r = context.getResources();
            float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                    dpValue, r.getDisplayMetrics());
            return (int) px;
        }
    }
    
  3. 现在,可以通过自定义属性在任何布局中轻松使用它:

    <YOUR_PACKAGE.CustomTextView
        android:id="@+id/id_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:drawable="@drawable/drawable_home_selector"
        app:drawableHeight="24dp"
        app:drawableWidth="24dp"
        app:position="1" />
    

    你可以用 Button,EditText 和 RadioButton 做类似的事情,因为它们是从 TextView 派生的。

如有错误请指出,谢谢。

注意事项:
在项目根目录的 build.gradle 文件中的 gradle 插件版本须高于 1.5.0,现在一般 3.x 的 Android Studio 新建的项目的 Gradle 版本都比这高,旧项目如需要升级,建议翻墙或者下载离线文件。

// SVG:适用于 Gradle 的 Android 插件 1.5.0 或更高版本
buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.2'
    }
}

Android :vector-asset-studio
stackoverflow :Binary XML file line #1: invalid drawable tag vector

猜你喜欢

转载自blog.csdn.net/u013323045/article/details/80548776