Android API 16及更高版本上的“层列表"中的矢量可绘制对象 [英] Vector Drawables in Layer List on Android API 16 and higher

查看:58
本文介绍了Android API 16及更高版本上的“层列表"中的矢量可绘制对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Android上较旧的API版本上绘制矢量时遇到了一些麻烦.每当活动开始时,我都需要在运行时更改可绘制对象,以加载相应的svg文件.

I am having some trouble with vectors drawable on older API version in Android. I need to change drawables at runtime each time the activity starts should load the corresponding svg file.

这是我的图层列表:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

<item >
    <shape android:shape="oval">
        <size android:height="50dp" android:width="50dp"/>
        <!-- fill color -->
        <solid android:color="@color/white" />
    </shape>
</item>
<item
    android:id="@+id/avatar"
    android:drawable="@drawable/dog" //I need to change this at run time
    android:bottom="10dp"
    android:left="10dp"
    android:right="10dp"
    android:top="10dp"/>

在活动中,我正在使用

static {
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}

到目前为止,我正在使用图层可绘制来选择xml文件并更改svg,但是我遇到兼容性问题,因为 layerDrawable.setDrawble()仅在API级别> = 23中可用

So far I am using layer drawable to pick the xml file and change the svg but I am having compatibility issues as layerDrawable.setDrawble() is only available in API level >= 23

 layerDrawable = (LayerDrawable) ContextCompat.getDrawable(this, R.drawable.seekbar_thumb);
 Drawable avatar = (Drawable) ContextCompat.getDrawable(this, getUserAvatarId());
 layerDrawable.setDrawable(0, avatar);

推荐答案

此解决方案很简单.这个概念是我想在活动的 onCreate()状态下更改搜索栏的拇指.我的搜索栏的拇指是我发布的可绘制文件.基本上,它会加载带有白色笔划的SVG文件,具体取决于用户该SVG应该是可变的.

The solution of this is simple. The concept is that I wanted to change the thumb of a seek bar in the onCreate() state of an activity. The thumb of my seek bar is drawable file the one I posted. Basically, it loads an SVG file with a white stroke around it, depending on the user this SVG should be changeable.

对于Android API> = 16,解决方案如下:

For Android API >= 16 the solution is the following:

layerDrawable = (LayerDrawable) ContextCompat.getDrawable(this, R.drawable.seekbar_thumb);
Drawable avatar = VectorDrawableCompat.create(getResources(), getUserAvatarId(), null);
layerDrawable.mutate(); //not share its state with other drawables
layerDrawable.setDrawableByLayerId(R.id.avatar, avatar);
layerDrawable.invalidateSelf(); //inform the layer drawable when it needs to redraw
seekBar.setThumb(layerDrawable);

函数 setDrawableById(int,drawable)的类型为boolean,如果更改了该图层的drawable,则返回true;否则,返回false!然后,在这种情况下,您需要用新的可绘制文件替换视图 seekBar.setThumb(layerDrawable);

The Function setDrawableById(int, drawable) is of type boolean and returns either true if the drawable of the layer is changed or false if is not! Then you need to replace the view with the new drawable file in this case seekBar.setThumb(layerDrawable);

这篇关于Android API 16及更高版本上的“层列表"中的矢量可绘制对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆