3 回答

TA貢獻(xiàn)2016條經(jīng)驗(yàn) 獲得超9個(gè)贊
drawable是一個(gè)橢圓形,是ImageView的背景
Drawable從imageView使用中獲取getBackground():
Drawable background = imageView.getBackground();
檢查通常的嫌疑人:
if (background instanceof ShapeDrawable) {
// cast to 'ShapeDrawable'
ShapeDrawable shapeDrawable = (ShapeDrawable) background;
shapeDrawable.getPaint().setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof GradientDrawable) {
// cast to 'GradientDrawable'
GradientDrawable gradientDrawable = (GradientDrawable) background;
gradientDrawable.setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof ColorDrawable) {
// alpha value may need to be set again after this call
ColorDrawable colorDrawable = (ColorDrawable) background;
colorDrawable.setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
}
緊湊版:
Drawable background = imageView.getBackground();
if (background instanceof ShapeDrawable) {
((ShapeDrawable)background).getPaint().setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof GradientDrawable) {
((GradientDrawable)background).setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof ColorDrawable) {
((ColorDrawable)background).setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
}
請注意,不需要進(jìn)行空檢查。
但是,mutate()如果在其他地方使用它們,則應(yīng)在修改之前使用drawables。(默認(rèn)情況下,從XML加載的drawable共享相同的狀態(tài)。)

TA貢獻(xiàn)1817條經(jīng)驗(yàn) 獲得超6個(gè)贊
這樣做:
ImageView imgIcon = findViewById(R.id.imgIcon); GradientDrawable backgroundGradient = (GradientDrawable)imgIcon.getBackground(); backgroundGradient.setColor(getResources().getColor(R.color.yellow));

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超13個(gè)贊
現(xiàn)在更簡單的解決方案是使用您的形狀作為背景,然后通過編程方式更改其顏色
view.getBackground().setColorFilter(Color.parseColor("#343434"),?PorterDuff.Mode.SRC_OVER)
編輯:
就像評論中正確指出的人一樣PorterDuff.Mode.SRC_ATOP
,如果您的背景有圓角等,您可能會(huì)想要使用。
- 3 回答
- 0 關(guān)注
- 541 瀏覽
添加回答
舉報(bào)