【问题标题】:Change Fill Color or strokeColor for Vector Layout Programmatically以编程方式更改矢量布局的填充颜色或描边颜色
【发布时间】:2016-12-02 06:07:52
【问题描述】:

以编程方式更改笔触或填充颜色。是否可以通过编程方式更改矢量的填充颜色,但不能更改描边颜色。

vector_icon.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">

    <path
        android:strokeColor="#FF000000"
        android:strokeWidth="0.8"
        android:strokeAlpha="0.5"
        android:strokeLineJoin="round"
        android:strokeLineCap="round"
        android:strokeMiterLimit="1"
        android:pathData="M12,22c1.1,0 2,-0.9 2,-2h-4c0,1.1 0.89,2 2,2zM18,16v-5c0,-3.07 -1.64,-5.64 -4.5,-6.32L13.5,4c0,-0.83 -0.67,-1.5 -1.5,-1.5s-1.5,0.67 -1.5,1.5v0.68C7.63,5.36 6,7.92 6,11v5l-2,2v1h16v-1l-2,-2z"/>

</vector>

我使用矢量绘图的图像视图。

   <ImageView
                            android:id="@+id/ivNotification"
                            android:layout_width="@dimen/navigation_icon_size"
                            android:layout_height="@dimen/navigation_icon_size"
                            android:scaleType="fitXY"
                            android:src="@drawable/vector_icon_notification"/>

我尝试将 VectorDrawable 转换为 GradientDrawable,但它会抛出类转换执行。

GradientDrawable gdFavourite = (GradientDrawable) ivFavourite.getDrawable();
                gdFavourite.setStroke(1, colorPrimary);
                gdFavourite.setColor(colorPrimary);
                tvFavourite.setTextColor(colorPrimary);

java.lang.ClassCastException: android.graphics.drawable.VectorDrawable 不能转换为 android.graphics.drawable.LayerDrawable

【问题讨论】:

标签: java android


【解决方案1】:

您在这里没有太多选择,您只需要接受ivFavourite.getDrawable(); 返回VectorDrawable 并且不允许您通过代码更改 Storke 的事实。

您可以查看该课程的完整文档here

解决它的一种可能解决方案是从其他 xml 获取 VectorDrawable 并通过调用覆盖现有的:ivFavourite.setBackgroundDrawable(myVectorDrawable)

【讨论】:

  • 为 imageview 更改 BackgroundDrawable 我需要创建两个可绘制的任何其他选项?
  • @PrashantSrivastav 您可以将 backgroundDrawable 设置为您喜欢的任何内容,但是如果您通过 xml 设置它,则需要将其转换为您设置的内容,如果它是 VectorDrawable,则没有什么神奇的方法可以将其传输为 LayerDrawable
猜你喜欢
  • 1970-01-01
  • 2021-05-23
  • 1970-01-01
  • 2014-08-11
  • 2013-03-18
  • 2020-01-29
  • 1970-01-01
  • 1970-01-01
  • 2015-05-17
相关资源
最近更新 更多