我正在使用 android 支持库,除了数量有限的使用主题中定义的颜色 accentColor 着色的小部件外,我还想为我在我的应用程序中使用的其他一些可绘制对象着色。 我通过以下代码执行此操作:
public class ActivityTest extends AppCompatActivity {
protected void tintDrawable(int color, int drawableId) {
Drawable drawable = DrawableCompat.wrap(ContextCompat.getDrawable(this, drawableId));
DrawableCompat.setTint(drawable, color);
}
protected void tintDrawables() {
int colorPrimary = getColorFromAttributeId(this, R.attr.colorPrimary);
tintDrawable(colorPrimary, R.drawable.drawable_1);
tintDrawable(colorPrimary, R.drawable.drawable_2);
tintDrawable(colorPrimary, R.drawable.drawable_3);
tintDrawable(colorPrimary, R.drawable.drawable_4);
tintDrawable(colorPrimary, R.drawable.drawable_5);
tintDrawable(colorPrimary, R.drawable.drawable_6);
}
public static int getColorFromAttributeId(Context context, int resourceAttributeId) {
int[] attributes = new int[] { resourceAttributeId };
TypedArray typedArray = context.obtainStyledAttributes(attributes);
int color = typedArray.getColor(0, Color.TRANSPARENT);
typedArray.recycle();
return color;
}
protected void doSetPreferencedThemeOnCreateSetContentView(Bundle savedInstanceState, int layoutResourceId) {
/* Catch 22:
* This order must be used otherwise an exception is thrown or theme is not applied.
* 1. setTheme()
* 1.b tintDrawables only after the theme is known we can get the color
* 2. onCreate()
* 3. setContentView() *
* 4. setSupportActionBar() */
// Apply theme. This must be done before super.onCreate()
setTheme(R.style.Theme_Custom_Theme); // in real case theme is retrieved from preferences
tintDrawables();
super.onCreate(savedInstanceState);
setContentView(layoutResourceId);
}
@Override
public void onCreate(Bundle savedInstanceState)
{
doSetPreferencedThemeOnCreateSetContentView(savedInstanceState, R.layout.activity_test);
}
}
看似复杂,其实很好理解。问题是我的可绘制对象是“随机”着色的。有些是,有些不是,并保留原始 png 中设置的颜色。更糟糕的是,如果我离开 Activity 再回来,结果可能会有所不同。可能会有更多或更少的正确着色的可绘制对象。 我猜着色是异步的,布局是在着色应用于所有可绘制对象之前创建的。但这只是一个猜测。 这个问题很烦人,因为我的 UI 取决于正确的着色,白色背景上的白色图标用处不大。两者都不是黑色的黑色。 如何强制对可绘制对象进行正确着色?
最佳答案
我知道这是旧的,但我遇到了同样的问题。在可绘制对象上调用 mutate() 可确保它不会与任何其他可绘制对象共享其状态。来自文档:
“默认情况下,从同一资源加载的所有可绘制对象实例共享一个公共(public)状态;如果您修改一个实例的状态,所有其他实例将收到相同的修改”
在我的例子中,这导致了随机的着色问题。
关于android - 如何修复零星的可绘制着色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41150482/