的Android Studio版本2.1,gradle這個版本2.1.0,如果你發現任何誤解:)編程着色,支持向量
我感到困惑的支持庫23.3.0支持向量請指正。具體來說,我想要做的是以編程方式着色圖像按鈕,其src被定義爲矢量繪製。從我可以告訴這是不可能的現在前棒棒糖。
我已看過一些相關的職位有關的變化: 23.2.0 announcement and changes:
由於Android的支持庫23.3.0中,支持向量繪圖資源只能通過應用程序加載:srcCompat或setImageResource()。
上述是否意味着矢量個XML只能通過srcCompat或setImageResource()被用於預棒棒糖,因此不能動態着色?
這是我的基本的圖像按鈕:
<ImageButton
android:id="@+id/nav_header_exit_community_button"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:background="@null"/>
作品在棒棒糖及以上的只有:
Drawable bg = ContextCompat.getDrawable(a, R.drawable.ic_exit_to_app_24dp);
DrawableCompat.setTint(bg, headerTitleColor);
exitButton.setImageDrawable(bg);
嘗試這種預棒棒糖拋出: android.content.res.Resources$NotFoundException: File res/drawable/ic_exit_to_app_24dp.xml from drawable resource ID #0x7f0200bf
同樣適用在棒棒糖和以上只有
Drawable bg = ContextCompat.getDrawable(a, R.drawable.ic_exit_to_app_24dp);
DrawableCompat.setTint(bg, headerTitleColor);
exitButton.setImageResource(R.drawable.ic_exit_to_app_24dp);
這會在預棒棒糖上引發同樣的錯誤。
但是,如果我刪除vectorDrawables.useSupportLibrary = true
如指出by Ian Lake here,與具有生成工具自動生成預棒棒糖設備png格式的意圖,的PNG圖像不會在着色前棒棒糖,所以我回方形之一。
我也嘗試過通過srcCompat
指定矢量並以編程方式檢索它,但我不認爲我已經能夠實現這一點,即使它在後Lollipop上工作,如果使用src
代替矢量。
所以對於23.3.0的情況似乎是:
後棒棒糖:
src
和srcCompat
接受的載體,只有src
可以從視圖中爲編程着色的可繪製檢索 。 使用getDrawable可以引用代碼中的矢量,並且它們可以是有色的 。Pre-Lollipop:srcCompat只能接受矢量,不能從視圖中以編程方式檢索 。
setImageResource
可以 接受載體,但僅限於vectorDrawables.useSupportLibrary = false
,並且着色不起作用。除非vectorDrawables.useSupportLibrary = false
和着色 不起作用,否則類似地引用代碼中的矢量不是 。
使用上的所有版本工作的PNG:
Drawable bg = ContextCompat.getDrawable(a, R.drawable.ic_nav_exit_community);
DrawableCompat.setTint(bg, headerTitleColor);
exitButton.setImageDrawable(bg);
附錄:
這種技術也適用於後的棒棒糖,但前棒棒堂和其他人一樣,我得到可繪製,但不可着色:
Drawable bg = VectorDrawableCompat.create(a.getResources(), R.drawable.ic_exit_to_app_24dp, null);
DrawableCompat.setTint(bg, headerTitleColor);
exitButton.setImageDrawable(bg);
同類解決方案:
由於John's答案迄今唯一很簡單的方法,我可以拿出來着色,支持向量是設置彩色濾光片就可以了 - 這意味着DrawableCompat.setTint()
功能似乎是如果所討論的drawable是一個支持向量,那麼對我而言不起作用。我不確定這是否是一個合法的錯誤,預期的行爲,或者如果我只是做錯了什麼!
這是我跟去暫時解決方案:
Drawable bg;
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
bg = VectorDrawableCompat.create(a.getResources(), R.drawable.ic_exit_to_app_24dp, null);
exitButton.setColorFilter(headerTitleColor, PorterDuff.Mode.MULTIPLY);
}
else {
bg = ContextCompat.getDrawable(a, R.drawable.ic_exit_to_app_24dp);
DrawableCompat.setTint(bg, headerTitleColor);
}
exitButton.setImageDrawable(bg);
請問,如果你使用Vector COMPAT庫中創建您的drawble工作?即VectorDrawableCompat.create(getResources(),R.drawable.ic_action_add,null) – Kuffs
我已經更新了我的答案,看起來像是另一種技術(!)來做同樣的事情,但設色它不起作用在pre-L –
這不是另一個技術,這是如何創建'VectorDrawableCompat',並且如果您閱讀'DrawableCompat'文檔,您會看到[this](http://pastebin.com/CzEbnP9k)正常工作 – pskink