[英]Android: How to set stroke color for vector drawable programmatically
[英]programmatically update android Vector Drawable
我有一個 VectorDrawable 由 9 個矩形組成。 這在 drawables 文件夾中定義為 XML。 我將此設置為我在 xml 中聲明的 ImageView 的背景。 android:src="@drawable/squares00"
我想在運行時以編程方式更改一個或多個方塊的顏色。 我知道有辦法使用 VectorDrawable 動畫來做到這一點。 但是我想知道是否有更簡單的方法可以在 java 中訪問我的 vectorDrawable,更新其屬性(為矩形設置一種或多種填充顏色),然后使用更新的 VectoDrawable 更新圖像背景。 我的目標是 Android API 21(棒棒糖)
簡而言之:
長:
1.您沒有訪問權限
查看VectorDrawable的源代碼將顯示內部元素信息存儲在內部私有狀態類VectorDrawableState
。 按名稱公開內部元素的唯一方法是getTargetByName
,但不幸的是它是包私有的(默認) - 你不能使用它(除非你使用反射)。
2. AnimatedVectorDrawable只有訪問權限
getTargetByName
僅被AnimatedVectorDrawable 使用,我們可以通過搜索該方法的用法來找到。
所以現在我們看到這是唯一可用的選項,例如,我們可以嘗試以下將元素“rect2”的顏色從白色更改為黑色:
change_color.xml:
<set xmlns:android="http://schemas.android.com/apk/res/android">
<objectAnimator
android:duration="0"
android:propertyName="fillColor"
android:valueFrom="@color/white"
android:valueTo="@color/black"/>
</set>
動畫.xml:
<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/vectordrawable" >
<target
android:name="rect2"
android:animation="@anim/change_color" />
</animated-vector>
並使用此處描述的方法。
筆記
如果以上仍然不適合您,您可以嘗試以下操作:
getTargetByName
使用反射來獲取內部元素。 您需要確保首先mutate
對象。試試這個庫https://github.com/devendroid/VectorChildFinder
val vector = VectorChildFinder(context, R.drawable.drawable_id, imageView)
vector.findPathByName("path_name").fillColor = Color.RED
<vector
...>
<path
android:name="path_name"
android:fillColor="#000"
android:pathData="..." />
</vector>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.