Android通过代码修改Drawable后变为黑白的问题求助
你的问题出在Android 5.0+系统中,调用getResources().getDrawable(R.drawable.chef_white, getContext().getTheme())时,系统会自动应用当前主题中配置的Drawable tint(比如FAB默认的色调),导致原本的白色厨师图标被主题色调覆盖,变成黑白样式。而初始加载图标时,XML配置的Drawable通常不会被自动应用这种主题tint,所以显示正常。
解决方案
方法1:使用AppCompatResources获取Drawable(推荐)
借助AndroidX AppCompat库的AppCompatResources.getDrawable()方法,它会自动处理Drawable的色调兼容问题,避免主题tint干扰,同时无需判断API版本:
HomePageActivity.getChefButton().setImageDrawable(AppCompatResources.getDrawable(getContext(), R.drawable.chef_white));
这个方法会保留Drawable本身的颜色属性,适配所有Android版本,代码更简洁可靠。
方法2:清除FAB的Image Tint
如果不想依赖AppCompat库,可以先清除FAB的图片色调设置,再加载Drawable:
// 清除FAB的图片色调,让Drawable显示原本颜色 HomePageActivity.getChefButton().setImageTintList(null); // 加载并设置Drawable if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { HomePageActivity.getChefButton().setImageDrawable(getResources().getDrawable(R.drawable.chef_white, getContext().getTheme())); } else { HomePageActivity.getChefButton().setImageDrawable(getResources().getDrawable(R.drawable.chef_white)); }
注意:如果后续切换其他图标需要应用色调,需要重新设置imageTintList。
方法3:独立Drawable状态并清除色调
通过mutate()方法让Drawable成为独立实例,再清除其色调,避免被主题或其他实例影响:
Drawable chefDrawable; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { chefDrawable = getResources().getDrawable(R.drawable.chef_white, getContext().getTheme()); } else { chefDrawable = getResources().getDrawable(R.drawable.chef_white); } // 让Drawable独立,不共享状态 chefDrawable.mutate(); // 清除色调,恢复原本颜色 chefDrawable.setTintList(null); HomePageActivity.getChefButton().setImageDrawable(chefDrawable);
内容的提问来源于stack exchange,提问作者Nadav Holtzman
相关产品推荐
相关产品推荐

